Esempio n. 1
0
        public void FetchAll_FluentPocos()
        {
            List <FluentUser> users = CqlClient.Fetch <FluentUser>();

            users.ShouldAllBeEquivalentTo(TestDataHelper.Users, opt => opt.AccountForTimestampAccuracy().Using(FluentUserToTestUserMatchingRule.Instance).ExcludingMissingProperties());
            users.Select(u => u.SomeIgnoredProperty).Should().OnlyContain(p => p == null);
        }
Esempio n. 2
0
        public async void InsertAsync_FluentPoco()
        {
            // Get a "new" user by using the test data from an existing user and changing the primary key
            TestUser user    = TestDataHelper.Users.First();
            var      newUser = new FluentUser
            {
                Id               = Guid.NewGuid(),
                Name             = user.Name,
                Age              = user.Age,
                CreatedDate      = user.CreatedDate,
                IsActive         = user.IsActive,
                LastLoginDate    = user.LastLoginDate,
                LoginHistory     = user.LoginHistory,
                LuckyNumbers     = user.LuckyNumbers,
                ChildrenAges     = user.ChildrenAges,
                FavoriteColor    = user.FavoriteColor,
                TypeOfUser       = user.TypeOfUser,
                PreferredContact = user.PreferredContactMethod,
                HairColor        = user.HairColor
            };

            // Insert the new user
            await CqlClient.InsertAsync(newUser);

            // Fetch and verify
            var foundUser = await CqlClient.SingleAsync <FluentUser>("WHERE userid = ?", newUser.Id);

            foundUser.ShouldBeEquivalentTo(newUser, opt => opt.AccountForTimestampAccuracy());
        }
Esempio n. 3
0
        public async void FetchAsyncAll_FluentPocos_WithOptions()
        {
            List <FluentUser> users = await CqlClient.FetchAsync <FluentUser>(new CqlQueryOptions().DoNotPrepare());

            users.ShouldAllBeEquivalentTo(TestDataHelper.Users, opt => opt.AccountForTimestampAccuracy().Using(FluentUserToTestUserMatchingRule.Instance).ExcludingMissingProperties());
            users.Select(u => u.SomeIgnoredProperty).Should().OnlyContain(p => p == null);
        }
Esempio n. 4
0
        public void FetchAll_FluentPocos_WithOptions()
        {
            List <FluentUser> users = CqlClient.Fetch <FluentUser>(new CqlQueryOptions().EnableTracing().SetConsistencyLevel(ConsistencyLevel.LocalQuorum));

            users.ShouldAllBeEquivalentTo(TestDataHelper.Users, opt => opt.AccountForTimestampAccuracy().Using(FluentUserToTestUserMatchingRule.Instance).ExcludingMissingProperties());
            users.Select(u => u.SomeIgnoredProperty).Should().OnlyContain(p => p == null);
        }
Esempio n. 5
0
        public void Update_Poco()
        {
            // Get an existing user from the DB
            Guid userId       = TestDataHelper.Users[1].UserId;
            var  userToUpdate = CqlClient.Single <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            userToUpdate.Should().NotBeNull();

            // Change some properties
            userToUpdate.Name          = "SomeNewName";
            userToUpdate.Age           = 186;
            userToUpdate.CreatedDate   = DateTimeOffset.UtcNow.AddHours(-1);
            userToUpdate.IsActive      = !userToUpdate.IsActive;
            userToUpdate.LastLoginDate = userToUpdate.LastLoginDate == null ? DateTimeOffset.UtcNow : (DateTimeOffset?)null;
            userToUpdate.LoginHistory.Add(DateTimeOffset.UtcNow);
            userToUpdate.LuckyNumbers.Add(137);
            userToUpdate.ChildrenAges.Add("SomeOtherChild", 5);
            userToUpdate.FavoriteColor    = Enum.GetValues(typeof(RainbowColor)).Cast <RainbowColor>().First(v => v != userToUpdate.FavoriteColor);
            userToUpdate.TypeOfUser       = userToUpdate.TypeOfUser == null ? UserType.Administrator : (UserType?)null;
            userToUpdate.PreferredContact = Enum.GetValues(typeof(ContactMethod)).Cast <ContactMethod>().First(v => v != userToUpdate.PreferredContact);
            userToUpdate.HairColor        = userToUpdate.HairColor == null ? HairColor.Black : (HairColor?)null;

            // Update
            CqlClient.Update(userToUpdate);

            // Fetch and verify
            var foundUser = CqlClient.Single <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            foundUser.ShouldBeEquivalentTo(userToUpdate, opt => opt.AccountForTimestampAccuracy());
        }
Esempio n. 6
0
        public void Execute_MixedBatch()
        {
            // Generate test user
            const int idx      = 20;
            var       testUser = new InsertUser
            {
                Id               = Guid.NewGuid(),
                Name             = string.Format("Name {0}", idx),
                Age              = idx,
                CreatedDate      = TestDataGenerator.GetDateTimeInPast(idx),
                IsActive         = idx % 2 == 0,
                LastLoginDate    = TestDataGenerator.GetNullableDateTimeInPast(idx),
                LoginHistory     = TestDataGenerator.GetList(idx, TestDataGenerator.GetDateTimeInPast),
                LuckyNumbers     = TestDataGenerator.GetSet(idx, i => i),
                ChildrenAges     = TestDataGenerator.GetDictionary(idx, i => string.Format("Child {0}", i), i => i),
                FavoriteColor    = TestDataGenerator.GetEnumValue <RainbowColor>(idx),
                TypeOfUser       = TestDataGenerator.GetEnumValue <UserType?>(idx),
                PreferredContact = TestDataGenerator.GetEnumValue <ContactMethod>(idx),
                HairColor        = TestDataGenerator.GetEnumValue <HairColor>(idx)
            };

            // Get id of existing user for deleting and updating
            Guid deleteId = TestDataHelper.Users[0].UserId;
            Guid updateId = TestDataHelper.Users[1].UserId;

            // Create batch of mixed statements and execute
            ICqlBatch batch = CqlClient.CreateBatch();

            batch.Insert(testUser);
            batch.Delete <InsertUser>("WHERE userid = ?", deleteId);
            batch.Update <InsertUser>("SET name = ? WHERE userid = ?", "SomeNewName", updateId);
            CqlClient.Execute(batch);
        }
Esempio n. 7
0
        public async void ExecuteAsync_Batch()
        {
            // Generate 3 test users
            var testUsers = Enumerable.Range(110, 3).Select(idx => new InsertUser
            {
                Id               = Guid.NewGuid(),
                Name             = string.Format("Name {0}", idx),
                Age              = idx,
                CreatedDate      = TestDataGenerator.GetDateTimeInPast(idx),
                IsActive         = idx % 2 == 0,
                LastLoginDate    = TestDataGenerator.GetNullableDateTimeInPast(idx),
                LoginHistory     = TestDataGenerator.GetList(idx, TestDataGenerator.GetDateTimeInPast),
                LuckyNumbers     = TestDataGenerator.GetSet(idx, i => i),
                ChildrenAges     = TestDataGenerator.GetDictionary(idx, i => string.Format("Child {0}", i), i => i),
                FavoriteColor    = TestDataGenerator.GetEnumValue <RainbowColor>(idx),
                TypeOfUser       = TestDataGenerator.GetEnumValue <UserType?>(idx),
                PreferredContact = TestDataGenerator.GetEnumValue <ContactMethod>(idx),
                HairColor        = TestDataGenerator.GetEnumValue <HairColor>(idx)
            }).ToList();

            // Create batch to insert users and execute
            ICqlBatch batch = CqlClient.CreateBatch();

            batch.Insert(testUsers[0]);
            batch.Insert(testUsers[1]);
            batch.Insert(testUsers[2]);
            await CqlClient.ExecuteAsync(batch);
        }
Esempio n. 8
0
        public void Fetch_Pocos_WithPredicateOnly()
        {
            // Lookup the first 2 users by id with only a FROM + WHERE
            TestUser[]       usersToGet = TestDataHelper.Users.Take(2).ToArray();
            List <PlainUser> users      = CqlClient.Fetch <PlainUser>("FROM users WHERE userid IN (?, ?)", usersToGet[0].UserId, usersToGet[1].UserId);

            users.ShouldAllBeEquivalentTo(usersToGet, opt => opt.AccountForTimestampAccuracy());
        }
Esempio n. 9
0
        public void Fetch_FluentPocos_WithPredicateOnly()
        {
            // Lookup users 3 and 4 with just a WHERE clause
            TestUser[] usersToGet = TestDataHelper.Users.Skip(2).Take(2).ToArray();

            List <FluentUser> users = CqlClient.Fetch <FluentUser>("WHERE userid IN (?, ?)", usersToGet[0].UserId, usersToGet[1].UserId);

            users.ShouldAllBeEquivalentTo(usersToGet, opt => opt.AccountForTimestampAccuracy().Using(FluentUserToTestUserMatchingRule.Instance).ExcludingMissingProperties());
            users.Select(u => u.SomeIgnoredProperty).Should().OnlyContain(p => p == null);
        }
Esempio n. 10
0
        public void Fetch_ExplicitColumnsPocos_WithCql()
        {
            List <ExplicitColumnsUser> users = CqlClient.Fetch <ExplicitColumnsUser>("SELECT * FROM users");

            // Compare to test users but exclude missing properties since we only queried a subset, as well as explicitly ignore
            // the name property because that should not have been mapped because it's missing a Column attribute
            users.ShouldAllBeEquivalentTo(TestDataHelper.Users, opt => opt.ExcludingMissingProperties().Excluding(u => u.Name));

            // All name properties should be null
            users.Select(u => u.Name).Should().OnlyContain(name => name == null);
        }
Esempio n. 11
0
        public void GetFirstOrDefault_Poco_WithCql()
        {
            // Get random first or default user and verify they are same as user from test data
            var user = CqlClient.FirstOrDefault <PlainUser>("SELECT * FROM users");

            user.ShouldBeEquivalentTo(TestDataHelper.Users.Single(u => u.UserId == user.UserId), opt => opt.AccountForTimestampAccuracy());

            // Get first or default where user id doesn't exist and make sure we get null
            var notExistingUser = CqlClient.FirstOrDefault <PlainUser>("SELECT * FROM users WHERE userid = ?", Guid.Empty);

            notExistingUser.Should().BeNull();
        }
Esempio n. 12
0
        public void GetFirstOrDefault_OneColumnFlattened_WithCql()
        {
            // Get random first or default name and make sure it was one from our test data
            var name = CqlClient.FirstOrDefault <string>("SELECT name FROM users");

            TestDataHelper.Users.Select(u => u.Name).Should().Contain(name);

            // Get random first or default login history for user that does not exist and make sure we get null
            var loginHistory = CqlClient.FirstOrDefault <List <DateTimeOffset> >("SELECT loginhistory FROM users WHERE userid = ?", Guid.Empty);

            loginHistory.Should().BeNull();
        }
Esempio n. 13
0
        public void GetSingleOrDefault_Poco_WithCql()
        {
            // Get a user that exists
            var user = CqlClient.SingleOrDefault <PlainUser>("SELECT * FROM users WHERE userid = ?", TestDataHelper.Users[1].UserId);

            user.ShouldBeEquivalentTo(TestDataHelper.Users[1], opt => opt.AccountForTimestampAccuracy());

            // Get a user that doesn't exist (using Guid.Empty as the Id)
            var notExistingUser = CqlClient.SingleOrDefault <PlainUser>("SELECT * FROM users WHERE userid = ?", Guid.Empty);

            notExistingUser.Should().BeNull();
        }
Esempio n. 14
0
        public void FetchAll_ExplicitColumnsPocos()
        {
            // We should be able to fetch explicit columns poco with no CQL (i.e. have it generated for us)
            List <ExplicitColumnsUser> users = CqlClient.Fetch <ExplicitColumnsUser>();

            // Compare to test users but exclude missing properties since we only queried a subset, as well as explicitly ignore
            // the name property because that should not have been mapped because it's missing a Column attribute
            users.ShouldAllBeEquivalentTo(TestDataHelper.Users, opt => opt.ExcludingMissingProperties().Excluding(u => u.Name));

            // All name properties should be null
            users.Select(u => u.Name).Should().OnlyContain(name => name == null);
        }
Esempio n. 15
0
        public void Delete_Poco_NoPrimaryKey()
        {
            // Get an existing user from the DB that doesn't have a PK attribute defined on the POCO (i.e. InsertUser class)
            Guid userId       = TestDataHelper.Users[3].UserId;
            var  userToDelete = CqlClient.Single <InsertUser>("WHERE userid = ?", userId);

            userToDelete.Should().NotBeNull();

            Action deleteUser = () => CqlClient.Delete(userToDelete);

            deleteUser.ShouldThrow <InvalidOperationException>("no PK was specified and the assumed PK of 'id' is not a column on the POCO");
        }
Esempio n. 16
0
        public void GetSingleOrDefault_OneColumnFlattened_WithCql()
        {
            // Get the lucky numbers for a user that exists
            var luckyNumbers = CqlClient.SingleOrDefault <HashSet <int> >("SELECT luckynumbers FROM users WHERE userid = ?",
                                                                          TestDataHelper.Users[1].UserId);

            luckyNumbers.Should().BeEquivalentTo(TestDataHelper.Users[1].LuckyNumbers);

            // Get IsActive for a user that doesn't exist
            var isActive = CqlClient.SingleOrDefault <bool?>("SELECT isactive FROM users WHERE userid = ?", Guid.Empty);

            isActive.Should().NotHaveValue();
        }
Esempio n. 17
0
        public void Fetch_ExplicitColumnsPocos_WithPredicateOnly()
        {
            // Lookup users 5 and 6 with just a WHERE clause
            TestUser[] usersToGet = TestDataHelper.Users.Skip(4).Take(2).ToArray();

            List <ExplicitColumnsUser> users = CqlClient.Fetch <ExplicitColumnsUser>("WHERE userid IN (?, ?)", usersToGet[0].UserId, usersToGet[1].UserId);

            // Compare to test users but exclude missing properties since we only queried a subset, as well as explicitly ignore
            // the name property because that should not have been mapped because it's missing a Column attribute
            users.ShouldAllBeEquivalentTo(usersToGet, opt => opt.ExcludingMissingProperties().Excluding(u => u.Name));

            // All name properties should be null
            users.Select(u => u.Name).Should().OnlyContain(name => name == null);
        }
Esempio n. 18
0
        public void Fetch_DecoratedPocos_WithCql()
        {
            List <DecoratedUser> users = CqlClient.Fetch <DecoratedUser>("SELECT * FROM users");

            foreach (DecoratedUser user in users)
            {
                // Match users from UserId -> Id property and test that matching properties are equivalent
                TestUser testUser = TestDataHelper.Users.SingleOrDefault(u => u.UserId == user.Id);
                user.ShouldBeEquivalentTo(testUser, opt => opt.ExcludingMissingProperties());

                // Also make sure that ignored property was ignored
                user.AnUnusedProperty.Should().NotHaveValue();
            }
        }
Esempio n. 19
0
        public void GetSingle_Poco_WithCql()
        {
            // Get a user that exists
            var user = CqlClient.Single <PlainUser>("SELECT * FROM users WHERE userid = ?", TestDataHelper.Users[0].UserId);

            user.ShouldBeEquivalentTo(TestDataHelper.Users[0], opt => opt.AccountForTimestampAccuracy());

            // Get a user that shouldn't exist (using Guid.Empty as the Id)
            Action getUser = () =>
            {
                var notExistingUser = CqlClient.Single <PlainUser>("SELECT * FROM users WHERE userid = ?", Guid.Empty);
            };

            getUser.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 20
0
        public async void UpdateAsync_Poco_NoPrimaryKey()
        {
            // Get an existing user from the DB that doesn't have a PK attribute defined on the POCO (i.e. InsertUser class)
            Guid userId       = TestDataHelper.Users[2].UserId;
            var  userToUpdate = await CqlClient.SingleAsync <InsertUser>("WHERE userid = ?", userId);

            userToUpdate.Should().NotBeNull();

            Func <Task> updateUser = async() =>
            {
                await CqlClient.UpdateAsync(userToUpdate);
            };

            updateUser.ShouldThrow <InvalidOperationException>("no PK was specified and the assumed PK of 'id' is not a column on the POCO");
        }
Esempio n. 21
0
        public void GetSingle_OneColumnFlattened_WithCql()
        {
            // Get the name for a user that exists
            var name = CqlClient.Single <string>("SELECT name FROM users WHERE userid = ?", TestDataHelper.Users[2].UserId);

            name.Should().Be(TestDataHelper.Users[2].Name);

            // Get the type of user for a user that doesn't exist
            Action getUserType = () =>
            {
                var userType = CqlClient.Single <UserType?>("SELECT typeofuser FROM users WHERE userid = ?", Guid.Empty);
            };

            getUserType.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 22
0
        public void GetFirst_Poco_WithCql()
        {
            // Get random first user and verify they are same as the user from test data
            var user = CqlClient.First <PlainUser>("SELECT * FROM users");

            user.ShouldBeEquivalentTo(TestDataHelper.Users.Single(u => u.UserId == user.UserId), opt => opt.AccountForTimestampAccuracy());

            // Get first user where user id doesn't exist and verify it throws
            Action getUser = () =>
            {
                var notExistingUser = CqlClient.First <PlainUser>("SELECT * FROM users WHERE userid = ?", Guid.Empty);
            };

            getUser.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 23
0
        public void GetFirst_OneColumnFlattened_WithCql()
        {
            // Get random first created date and make sure it was one from our test data
            var createdDate = CqlClient.First <DateTimeOffset>("SELECT createddate FROM users");

            TestDataHelper.Users.Select(u => u.CreatedDate.ToMillisecondPrecision()).Should().Contain(createdDate);

            // Verify getting random first for user that doesn't exist throws
            Action getUserId = () =>
            {
                var userId = CqlClient.First <Guid>("SELECT userid FROM users WHERE userid = ?", Guid.Empty);
            };

            getUserId.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 24
0
        public void FetchAll_DecoratedPocos_WithOptions()
        {
            // We should be able to get all the decorated POCOs without any CQL (i.e. have it generated for us)
            List <DecoratedUser> users = CqlClient.Fetch <DecoratedUser>(CqlQueryOptions.New().DisableTracing());

            foreach (DecoratedUser user in users)
            {
                // Match users from UserId -> Id property and test that matching properties are equivalent
                TestUser testUser = TestDataHelper.Users.SingleOrDefault(u => u.UserId == user.Id);
                user.ShouldBeEquivalentTo(testUser, opt => opt.ExcludingMissingProperties());

                // Also make sure that ignored property was ignored
                user.AnUnusedProperty.Should().NotHaveValue();
            }
        }
Esempio n. 25
0
        public void Delete_Poco_WithCql()
        {
            // Pick an existing user from the DB and verify they currently exist (sanity check)
            Guid userId       = TestDataHelper.Users[5].UserId;
            var  userToDelete = CqlClient.Single <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            userToDelete.Should().NotBeNull();

            // Delete using CQL string (no POCO passed here, just CQL + params)
            CqlClient.Delete <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            // Verify user is actually deleted
            var foundUser = CqlClient.SingleOrDefault <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            foundUser.Should().BeNull();
        }
Esempio n. 26
0
        public void Delete_Poco()
        {
            // Get an existing user from the DB
            Guid userId       = TestDataHelper.Users[1].UserId;
            var  userToDelete = CqlClient.Single <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            userToDelete.Should().NotBeNull();

            // Delete
            CqlClient.Delete(userToDelete);

            // Verify user is gone
            var foundUser = CqlClient.SingleOrDefault <UserWithPrimaryKeyDecoration>("WHERE userid = ?", userId);

            foundUser.Should().BeNull();
        }
Esempio n. 27
0
        public async void GetSingleAsync_OneColumnFlattened_WithCql()
        {
            // Get the name for a user that exists
            var name = await CqlClient.SingleAsync <string>("SELECT name FROM users WHERE userid = ?", TestDataHelper.Users[2].UserId);

            name.Should().Be(TestDataHelper.Users[2].Name);

            // Get the type of user for a user that doesn't exist
            Func <Task> getUserType = async() =>
            {
                var userType = await CqlClient.SingleAsync <UserType?>("SELECT typeofuser FROM users WHERE userid = ?", Guid.Empty)
                               .ConfigureAwait(false);
            };

            getUserType.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 28
0
        public async void GetSingleAsync_Poco_WithCql()
        {
            // Get a user that exists
            var user = await CqlClient.SingleAsync <PlainUser>("SELECT * FROM users WHERE userid = ?", TestDataHelper.Users[0].UserId);

            user.ShouldBeEquivalentTo(TestDataHelper.Users[0], opt => opt.AccountForTimestampAccuracy());

            // Get a user that shouldn't exist (using Guid.Empty as the Id)
            Func <Task> getUser = async() =>
            {
                var notExistingUser = await CqlClient.SingleAsync <PlainUser>("SELECT * FROM users WHERE userid = ?", Guid.Empty)
                                      .ConfigureAwait(false);
            };

            getUser.ShouldThrow <InvalidOperationException>();
        }
Esempio n. 29
0
        public void Fetch_DecoratedPocos_WithPredicateOnly()
        {
            // Lookup users 3 and 4 with just a WHERE clause
            TestUser[]           usersToGet = TestDataHelper.Users.Skip(2).Take(2).ToArray();
            List <DecoratedUser> users      = CqlClient.Fetch <DecoratedUser>("WHERE userid IN (?, ?)", usersToGet[0].UserId, usersToGet[1].UserId);

            foreach (DecoratedUser user in users)
            {
                // Match users from UserId -> Id property and test that matching properties are equivalent
                TestUser testUser = usersToGet.SingleOrDefault(u => u.UserId == user.Id);
                user.ShouldBeEquivalentTo(testUser, opt => opt.ExcludingMissingProperties());

                // Also make sure that ignored property was ignored
                user.AnUnusedProperty.Should().NotHaveValue();
            }
        }
Esempio n. 30
0
        public void Fetch_OneColumnFlattened_WithCql()
        {
            // Try regular value type
            List <int> ages = CqlClient.Fetch <int>("SELECT age FROM users");

            ages.Should().BeEquivalentTo(TestDataHelper.Users.Select(u => u.Age).ToList());

            // Try nullable type (truncate to ms to account for C* storing timestamps with ms precision)
            List <DateTimeOffset?> lastLogins = CqlClient.Fetch <DateTimeOffset?>("SELECT lastlogindate FROM users");

            lastLogins.Should().BeEquivalentTo(TestDataHelper.Users.Select(u => u.LastLoginDate.ToMillisecondPrecision()));

            // Try string -> enum conversion
            List <RainbowColor> faveColors = CqlClient.Fetch <RainbowColor>("SELECT favoritecolor FROM users");

            faveColors.Should().BeEquivalentTo(TestDataHelper.Users.Select(u => u.FavoriteColor));
        }