Typical tests for a Milos BusinessEntity

using EPS.Business.BusinessObjects; using EPS.Business.Names; using EPS.QualityTools.UnitTestFramework; using NUnit.Framework; using MyCompany.MySolution.BusinessObjects.User; using MyCompany.MySolution.QualityTools.UnitTestFramework; using MyCompany.MySolution.QualityTools.UnitTestFramework.Business; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Drawing; using System.Text; namespace MyCompany.MySolution.BusinessObjects.Tests.User { /// <summary> /// User Tests. /// </summary> [TestFixture] [EPS.QualityTools.UnitTestFramework.Business.BusinessObjectFixtureSetup(typeof(UserBusinessObject), typeof(UserBusinessEntity))] public class UserFixture : BusinessObjectFixture<UserBusinessEntity> { /// <summary> /// Keeps a collection of test user groups created to support tests on the user entity. /// </summary> private Collection<UserGroupBusinessEntity> m_TestUserGroups; #region Overrides /// <summary> /// Set up test data for properties on the entity. /// </summary> protected override void PopulateEntityBasicStateExpected() { this.EntityBasicState.Add("UserName", "jjones"); this.EntityBasicState.Add("Prefix", "Dr."); this.EntityBasicState.Add("Password", "1234"); this.EntityBasicState.Add("FirstName", "Joe"); this.EntityBasicState.Add("MiddleName", "Sidmond"); this.EntityBasicState.Add("LastName", "Jones"); this.EntityBasicState.Add("Suffix", "III"); this.EntityBasicState.Add("Title", "Professor"); this.EntityBasicState.Add("BirthDate", new DateTime(1970, 11, 25)); this.EntityBasicState.Add("Company", "Neverland Elementary School"); this.EntityBasicState.Add("Photo", new Bitmap(1, 1)); } /// <summary> /// Set up test data for entity collections. /// </summary> protected override void PopulateEntityCollectionsStateExpected() { List<Hashtable> addresses = new List<Hashtable>(); Hashtable address1 = new Hashtable(); address1.Add("Street", "123 Some St."); address1.Add("Street2", "Ste. 200"); address1.Add("City", "Houston"); address1.Add("State", "TX"); address1.Add("Zip", "12345"); address1.Add("TypeStrong", AddressType.Home); Hashtable address2 = new Hashtable(); address2.Add("Street", "22 Acacia Av."); address2.Add("City", "New York City"); address2.Add("State", "NY"); address2.Add("Zip", "12345"); address2.Add("TypeStrong", AddressType.Mailing); addresses.Add(address1); addresses.Add(address2); this.EntityCollectionsState.Add("Addresses", addresses); } /// <summary> /// Compares property actual value against expected value.. /// </summary> /// <param name="propertyName"></param> /// <param name="expectedValue"></param> /// <param name="actualValue"></param> /// <returns></returns> /// <remarks> /// Overridden so to handle the Photo property, which is a Bitmap. /// In such case, instead of comparing an object to another, we compare the size on the bitmap, /// just to make sure a bitmap got saved. /// </remarks> public override PropertyComparer ComparePropertyValue(string propertyName, object expectedValue, object actualValue) { PropertyComparer comparer; if (string.Compare(propertyName, "Photo", StringComparison.InvariantCultureIgnoreCase) == 0) { Bitmap expectedBitmap = (Bitmap)expectedValue; Bitmap actualBitmap = (Bitmap)actualValue; comparer = new PropertyComparer(propertyName, expectedBitmap.Size, actualBitmap.Size); } else { comparer = base.ComparePropertyValue(propertyName, expectedValue, actualValue); } return comparer; } /// <summary> /// Before creating any user entity, first create some user groups so that the user entities can have groups associated to it. /// </summary> protected override void OnBeforeNewTestEntitiesCreation() { base.OnBeforeNewTestEntitiesCreation(); // On the new user created, let's add two test user groups to it. this.m_TestUserGroups = BusinessObjectFixture<UserGroupBusinessEntity>.GetNewTestEntities<UserGroupFixture>(2); } /// <summary> /// Before saving an individual user entity, assign test user groups to it, as well as some exclusive permissions. /// </summary> /// <param name="testEntity">The user entity about to be saved.</param> protected override void OnBeforeSavingNewTestEntity(UserBusinessEntity testEntity) { base.OnBeforeSavingNewTestEntity(testEntity); StringBuilder nameBuilder = new StringBuilder(); nameBuilder.Append(testEntity.UserName); nameBuilder.Append(UserRolesFixture.TestEntitiesCreated.Count); testEntity.UserName = nameBuilder.ToString(); testEntity.UserGroups.Add(this.m_TestUserGroups[0].PK); testEntity.UserGroups.Add(this.m_TestUserGroups[1].PK); UserPermissionBusinessObject permissionBO = UserPermissionBusinessObject.NewInstance(); DataTable permissionsList = permissionBO.GetList().Tables[0]; Guid permission1 = (Guid)permissionsList.Rows[10]["PK_UserPermission"]; Guid permission2 = (Guid)permissionsList.Rows[11]["PK_UserPermission"]; // Add exclusive permissions to the user. ExclusivePermissionsBusinessItem userPermission1 = testEntity.ExclusivePermissions.Add(permission1); Assert.IsNotNull(userPermission1, "Failed adding exclusive permission to test user."); ExclusivePermissionsBusinessItem userPermission2 = testEntity.ExclusivePermissions.Add(permission2); Assert.IsNotNull(userPermission2, "Failed adding exclusive permission to test user."); userPermission1.Permission = UserExclusivePermissionAssignment.Denied; userPermission2.Permission = UserExclusivePermissionAssignment.Granted; testEntity.CommunicationInfo.Add(CommInfoType.Email, "test@yahoo.com"); } /// <summary> /// /// </summary> /// <returns></returns> protected override IBusinessEntity GetNewEntityPopulated() { UserBusinessEntity newEntity = base.GetNewEntityPopulated() as UserBusinessEntity; newEntity.CommunicationInfo.Add(CommInfoType.Email, "test@yahoo.com"); return newEntity; } /// <summary> /// After deleting user entities, delete the user groups created to support these tests. /// </summary> /// <param name="testEntities"></param> protected override void DeleteEntities(Collection<UserBusinessEntity> testEntities) { // Before deleting the user, we need to delete any scheduled item for that user. // This is only for unit test purposes. On the actual application, scheduled items // cannot be removed (so to keep history of the items). using (ScheduleItemBusinessObject scheduleItemBO = ScheduleItemBusinessObject.NewInstance()) { foreach (UserBusinessEntity userBE in testEntities) { this.RemoveScheduledItemsForUser(userBE.UserPK); } } base.DeleteEntities(testEntities); BusinessObjectFixture<UserGroupBusinessEntity>.DeleteTestEntities<UserGroupFixture>(); } /// <summary> /// Before delete basic entity. /// </summary> /// <param name="entity">The basic entity being deleted.</param> protected override void OnBeforeDelete(UserBusinessEntity entity) { this.RemoveScheduledItemsForUser(entity.UserPK); base.OnBeforeDelete(entity); } #endregion #region Test methods /// <summary> /// Tests the creation of a user with its basic information. /// </summary> [Test] public void CreateBasicUser() { this.TestNewEntityBasicData(); } /// <summary> /// Tests the creation of a user with collections. /// </summary> [Test] public void CreateUserWithCollections() { this.TestNewEntityWithCollections(); } /// <summary> /// Tests the creation of a user that belongs to user groups. /// </summary> [Test] public void CreateUserWithUserGroups() { // Create some test user groups to link to the test user. Collection<UserGroupBusinessEntity> testUserGroups = BusinessObjectFixture<UserGroupBusinessEntity>.GetNewTestEntities<UserGroupFixture>(2); UserBusinessEntity newEntity = (UserBusinessEntity)this.GetNewEntityPopulated(); // Link the two new user to the two test user groups create previously. Assert.IsNotNull(newEntity.UserGroups.Add(testUserGroups[0].PK), "Failed adding a group to the user."); Assert.IsNotNull(newEntity.UserGroups.Add(testUserGroups[1].PK), "Failed adding a group to the user."); // Can we save the entity? Assert.IsTrue(newEntity.Save(), "Failed saving entity."); try { // If we saved, now we reload the entity from the backend. UserBusinessEntity loadedEntity = UserBusinessEntity.LoadEntity(newEntity.PK); // Make sure we got the two user groups saved. Assert.AreEqual(2, loadedEntity.UserGroups.Count, "User should be assigned to two user groups."); // Make sure the user groups got saved with the right primary keys. Assert.IsTrue((loadedEntity.UserGroups[0].TargetFK == testUserGroups[0].PK || loadedEntity.UserGroups[0].TargetFK == testUserGroups[1].PK), "The user group saved is not the one that should have been saved."); Assert.IsTrue((loadedEntity.UserGroups[1].TargetFK == testUserGroups[0].PK || loadedEntity.UserGroups[1].TargetFK == testUserGroups[1].PK), "The user group saved is not the one that should have been saved."); } catch (Exception ex) { Assert.Fail("Failed loading and testing user entity with associated user groups: {0}", ex.Message); } finally { UserFixture.DeleteUserEntity(newEntity); } } /// <summary> /// Tests the creation of a user with exclusive permissions. /// </summary> [Test] public void CreateUserWithExclusivePermissions() { UserPermissionBusinessObject permissionBO = UserPermissionBusinessObject.NewInstance(); DataTable permissionsList = permissionBO.GetList().Tables[0]; Guid permission1 = (Guid)permissionsList.Rows[0]["PK_UserPermission"]; Guid permission2 = (Guid)permissionsList.Rows[1]["PK_UserPermission"]; // Get a basic user entity populated. UserBusinessEntity newEntity = (UserBusinessEntity)this.GetNewEntityPopulated(); // Add exclusive permissions to the user. ExclusivePermissionsBusinessItem userPermission1 = newEntity.ExclusivePermissions.Add(permission1); Assert.IsNotNull(userPermission1, "Should have gotten valid permission added to the user."); ExclusivePermissionsBusinessItem userPermission2 = newEntity.ExclusivePermissions.Add(permission2); Assert.IsNotNull(userPermission2, "Should have gotten valid permission added to the user."); userPermission1.Permission = UserExclusivePermissionAssignment.Denied; userPermission2.Permission = UserExclusivePermissionAssignment.Granted; // Can we save the entity? Assert.IsTrue(newEntity.Save(), "Failed saving user entity with exclusive permissions."); try { // If we saved, now we reload the entity from the backend. UserBusinessEntity loadedEntity = UserBusinessEntity.LoadEntity(newEntity.PK); // Make sure we got the two user groups saved. Assert.AreEqual(2, loadedEntity.ExclusivePermissions.Count, "User should have two exclusive permissions."); foreach (ExclusivePermissionsBusinessItem exclusivePermission in loadedEntity.ExclusivePermissions) { if (exclusivePermission.Permission == UserExclusivePermissionAssignment.Denied) { Assert.AreEqual(permission1, exclusivePermission.TargetFK); } else { Assert.AreEqual(permission2, exclusivePermission.TargetFK); } } } catch (Exception ex) { Assert.Fail("Failed loading and testing user entity with exclusive permissions: {0}", ex.Message); } finally { UserFixture.DeleteUserEntity(newEntity); } } /// <summary> /// Tests to make sure that a new user is required to change his/her password. /// </summary> [Test] public void NewUserIsRequiredToChangePassword() { try { Collection<UserBusinessEntity> testEntities = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(1); Assert.IsTrue(testEntities[0].PasswordChangeRequired, "A new user should be required to have the password changed."); } finally { BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } } /// <summary> /// Tests to make sure that a new user is required to change his/her password. /// </summary> [Test] public void TestInsertionInScheduleItemsWhenNewUserSaved() { UserBusinessEntity userBE = UserBusinessEntity.NewEntity(); try { userBE.FirstName = "myusername"; userBE.LastName = "lastname"; userBE.UserName = "username"; userBE.CommunicationInfo.Add(CommInfoType.Email, "a@eps-software.com"); //userBE.CommunicationInfo.Add("Email", "a@eps-software.com"); if (userBE.Save()) { ScheduleItemBusinessObject bo = ScheduleItemBusinessObject.NewInstance(); DataSet scheduleItems = bo.GetScheduleItemsForUser(userBE.UserPK); Assert.IsNotNull(scheduleItems, "A new item should be added to the scheduleitems table when a new user is created; so it must not be null"); //Assert.Greater(scheduleItems.Tables[0].Rows.Count, 0, "A new item should be added to the scheduleitems table when a new user is created; so there must be at least one row inserted"); } } finally { DeleteUserEntity(userBE); } } ///// <summary> ///// Tests to make sure that a new user is required to change his/her password. ///// </summary> //[Test] //public void TestGetUserByEmailAddress() //{ // try // { // UserBusinessEntity userBE = CreateSimpleUser(); // UserBusinessObject userBO = UserBusinessObject.NewInstance(); // Oncovance.Registry.BusinessObjects.User.ResidentUserBusinessObject iden; // Assert.IsNotNull(userBO.getUserByEmailAddress("a@eps-software.com"), "Method does not return user by email address"); // } // finally // { // BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); // } //} ///// <summary> ///// This method creates a simple user with the following settings ///// userBE.FirstName = "myusername"; ///// userBE.LastName = "lastname"; ///// userBE.UserName = "username"; ///// userBE.CommunicationInfo.Add(CommInfoType.Email, "a@eps-software.com"); ///// The user information is saved in the database ///// </summary> ///// <returns>Returns a simple UserBusiness entity with the following settings ///// userBE.FirstName = "myusername"; ///// userBE.LastName = "lastname"; ///// userBE.UserName = "username"; ///// userBE.CommunicationInfo.Add(CommInfoType.Email, "a@eps-software.com"); ///// </returns> //private UserBusinessEntity CreateSimpleUser() //{ // UserBusinessEntity userBE = null; // Collection<UserBusinessEntity> userTests = BusinessObjectFixture<UserGroupBusinessEntity>.GetNewTestEntities<1>(); // userBE = userTests[0]; // try // { // userBE.FirstName = "myusername"; // userBE.LastName = "lastname"; // userBE.UserName = "username"; // userBE.CommunicationInfo.Add(CommInfoType.Email, "a@eps-software.com"); // if (!userBE.Save()) // { // throw new AtomicSaveFailedException("Simple user entity was not saved"); // } // } // catch (System.Data.SqlClient.SqlException e) // { // throw e; // } // return userBE; //} /// <summary> /// Test adding communication info to a user. /// </summary> [Test] public void TestUserWithCommunicationInfo() { Collection<UserBusinessEntity> testEntities = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(1); UserBusinessEntity userBE = testEntities[0]; try { INameCommInfoEntity email = userBE.CommunicationInfo.Add(CommInfoType.Email, "claudio@eps-software.com"); Assert.IsNotNull(email, "Failed adding a new item to the CommunicationInfo collection."); IEntitySubItemCollectionItem item = email as IEntitySubItemCollectionItem; Assert.IsNotNull(item, "Failed casting INameCommInfoEntity to IEntitySubItemCollectionItem"); Assert.AreNotEqual(Guid.Empty, item.PK); Assert.IsTrue(userBE.Save(), "Failed saving user entity after adding contact info."); } finally { BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } } /// <summary> /// Tests the creation of test user entities. /// </summary> [Test] public void TestCreationOfTestUserEntity() { Collection<UserBusinessEntity> testUsers = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(2); Assert.AreEqual(2, testUsers.Count); BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } /// <summary> /// Tests the retrieval of users from a given group. /// </summary> [Test] public void TestsRetrievalOfUsersFromGroup() { try { Collection<UserBusinessEntity> sponsorsCreated = UserFixture.CreateUsersForTestByUserGroupType(FixedUserGroupType.Sponsors, 3); // Retrieve a list of all sponsors. DataSet sponsors = this.GetListOfSponsors(); // Go through the test sponsors we've created, and make sure they're included in the list. foreach (UserBusinessEntity newSponsorCreated in sponsorsCreated) { DataRow[] drs1 = sponsors.Tables[0].Select("FK_User = '" + newSponsorCreated.UserPK.ToString() + "'"); Assert.IsTrue(drs1.Length > 0, "A sponsors that we created is not included in the list of sponsors. " + "Every new sponsors created should have been retrieved when getting a list of sponsors."); } // Make sure that the test would fail in case the list doesn't have an invalid sponsors (fake pk). DataRow[] drs2 = sponsors.Tables[0].Select("PK_UserAndUserGroup = '" + Guid.NewGuid().ToString() + "'"); Assert.IsTrue(drs2.Length == 0, "The list of sponsors should not have a sponsors that's invalid in the system."); } finally { BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } } /// <summary> /// Tests the validation of a username/password. /// </summary> [Test] public void TestCheckForUserNamePasswordCombination() { Collection<UserBusinessEntity> testUsers = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(1); testUsers[0].UserName = "The User"; Assert.IsTrue(testUsers[0].Save(), "Failed saving test user."); try { UserBusinessEntity user = UserBusinessEntity.LoadEntity(testUsers[0].PK); using (UserBusinessObject userBO = UserBusinessObject.NewInstance()) { // Test a right combination. Assert.IsTrue(userBO.GetUserId(user.UserName, user.Password) == user.PK, "UserName/Password combination should be correct."); // Test a bad combination. Assert.IsTrue(userBO.GetUserId(user.UserName, "BAD PASSWORD") == Guid.Empty, "UserName/Password combination should be incorrect."); } } finally { BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } } /// <summary> /// Tests that password is required /// </summary> [Test] public void TestCheckForRequiredPassword() { Collection<UserBusinessEntity> testUsers = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(1); testUsers[0].UserName = "TestUser"; testUsers[0].Password = ""; // this is the password before it gets encrypted // Verify that we cannot save with an empty password Assert.IsFalse(testUsers[0].Save(), "Failed check for required password."); BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } /// <summary> /// Tests that password fails specified strength /// </summary> [Test] public void TestCheckPasswordFailsRegex() { Collection<UserBusinessEntity> testUsers = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(1); testUsers[0].UserName = "TestUser"; testUsers[0].Password = "foo"; // this is the password before it gets encrypted // Verify that we cannot save with a simple password Assert.IsFalse(testUsers[0].Save(), "Failed test for password strength."); BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } /// <summary> /// Tests that password meets specified strength /// </summary> [Test] public void TestCheckPasswordMeetsRegex() { Collection<UserBusinessEntity> testUsers = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(1); testUsers[0].UserName = "TestUser"; testUsers[0].Password = "P@rCheeZ!"; // this is the password before it gets encrypted // Verify that we can save with a password that exceeds the password regex Assert.IsTrue(testUsers[0].Save(), "Failed saving test user."); BusinessObjectFixture<UserBusinessEntity>.DeleteTestEntities<UserFixture>(); } #endregion #region Helper methods /// <summary> /// Gets a list of sponsors. /// </summary> /// <returns>DataSet containing list of sponsors.</returns> private DataSet GetListOfSponsors() { DataSet sponsors = null; using (UserBusinessObject userBO = UserBusinessObject.NewInstance()) { sponsors = userBO.GetUsersByFixedGroupType(FixedUserGroupType.Sponsors); } return sponsors; } /// <summary> /// Creates test users belonging to a specific type of user group. /// </summary> /// <param name="userGroupType">The type of user group the test users should belong to.</param> /// <param name="howMany">How many test entities to create.</param> /// <returns>Returns a collection of user business entities created.</returns> public static Collection<UserBusinessEntity> CreateUsersForTestByUserGroupType(FixedUserGroupType userGroupType, int howMany) { int testUsersToCreate = howMany; Guid userGroupId = UserGroupBusinessObject.GetFixedUserGroupId(userGroupType); Collection<UserBusinessEntity> usersCreated = new Collection<UserBusinessEntity>(); // Create a few users, and assign them to the sponsors user group. Collection<UserBusinessEntity> testUsers = BusinessObjectFixture<UserBusinessEntity>.GetNewTestEntities<UserFixture>(testUsersToCreate); foreach (UserBusinessEntity user in testUsers) { UserGroupBusinessItem newGroupItem = user.UserGroups.Add(userGroupId); Assert.IsNotNull(newGroupItem, "Failed adding {0} user group to the test user.", userGroupType.ToString()); // Keep track of the user created. usersCreated.Add(user); Assert.IsTrue(user.Save(), "Failed saving test user."); } return usersCreated; } /// <summary> /// Delete a given user entity from the database. /// </summary> /// <param name="newEntity">The user to delete.</param> private static void DeleteUserEntity(UserBusinessEntity newEntity) { // Get rid of the test data. using (UserBusinessObject userBO = UserBusinessObject.NewInstance()) { bool deletionSucceeded = true; string exceptionMessage = string.Empty; try { deletionSucceeded = userBO.Delete(newEntity.PK); } catch (Exception ex) { deletionSucceeded = true; exceptionMessage = ex.Message; } if (!deletionSucceeded) { Console.WriteLine("Failed deleting test user PK '{0}'. {1}", newEntity.PK.ToString(), exceptionMessage); } } BusinessObjectFixture<UserGroupBusinessEntity>.DeleteTestEntities<UserGroupFixture>(); } /// <summary> /// Removes all scheduled items for the specific user. /// </summary> /// <param name="userId"></param> private void RemoveScheduledItemsForUser(Guid userId) { using (ScheduleItemBusinessObject scheduleItemBO = ScheduleItemBusinessObject.NewInstance()) { DataSet scheduledItems = scheduleItemBO.GetScheduleItemsForUser(userId); foreach (DataRow item in scheduledItems.Tables[0].Rows) { Assert.IsTrue(scheduleItemBO.Delete((Guid)item["PK_ScheduleItem"]), "Failed deleting scheduled item for the user."); } } } #endregion } }


Last Updated: 8/1/2006