public void Test_GetEntityType() { using (LogGroup logGroup = LogGroup.Start("Testing the DataUtilities.GetEntityType function.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "Test Role"; user.Roles = Collection <TestRole> .Add(user.Roles, role); role.Users = Collection <TestUser> .Add(role.Users, user); PropertyInfo rolesProperty = user.GetType().GetProperty("Roles"); Type entityType = DataUtilities.GetEntityType(user, rolesProperty); Assert.AreEqual(entityType.FullName, role.GetType().FullName, "The types don't match #1."); PropertyInfo usersProperty = role.GetType().GetProperty("Users"); Type entityType2 = DataUtilities.GetEntityType(role, usersProperty); Assert.AreEqual(entityType2.FullName, user.GetType().FullName, "The types don't match #2."); } }
public void Test_Delete_EntityAndReference_Sync() { TestUser user = new TestUser(); Guid userID = user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); Guid roleID = role.ID = Guid.NewGuid(); role.Name = "Test Role"; user.Roles = new TestRole[] { role }; DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences(typeof(TestUser).Name, typeof(TestRole).Name); Assert.AreEqual(1, references.Count, "Incorrect number of references found."); DataAccess.Data.Deleter.Delete(user); EntityReferenceCollection references2 = DataAccess.Data.Referencer.GetReferences(typeof(TestUser).Name, typeof(TestRole).Name); Assert.AreEqual(0, references2.Count, "Reference not deleted."); }
public void ET_LazyRef_Serialization_Manual() { var defaultMeta = TestRole.TestUserProperty.DefaultMeta; var oldValue = defaultMeta.Serializable; defaultMeta.Unfreeze(); try { defaultMeta.Serializable = false; var role = new TestRole { TestUser = new TestUser { Id = 1, Name = "TestUser" } }; var roleCloned = ObjectCloner.Clone(role); var loaded = roleCloned.FieldExists(TestRole.TestUserProperty); Assert.IsFalse(loaded, "引用属性在 Serializable 设置为 false 时,不应该被序列化。"); } finally { defaultMeta.Serializable = oldValue; defaultMeta.Serializable = true; } }
public Simple() { Channel = new TestGuildTextChannel { Name = "general" }; Role = new TestRole { Name = "User" }; UserTest = new TestUser { Username = "******", Discriminator = "0001" }; Guild = new TestGuild { Name = "Senko", Channels = { Channel }, Roles = { Role }, Members = { UserTest } }; Guilds.Add(Guild); }
public void Test_Execute_Reference() { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "-- First Name -- "; user.LastName = "-- Last Name --"; //user.Username = "******"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "-- Test Role --"; user.Roles = new TestRole[] { role }; string newTypeName = "TestAccount"; EntityReference reference = DataAccess.Data.Referencer.GetActiveReferences(user)[0]; XmlDocument document = XmlUtilities.SerializeToDocument(reference); RenameTypeCommand command = new RenameTypeCommand(); command.TypeName = user.ShortTypeName; command.NewTypeName = newTypeName; command.Execute(document); EntityReference updatedReference = (EntityReference)XmlUtilities.DeserializeFromDocument(document, typeof(EntityReference)); Assert.AreEqual(newTypeName, updatedReference.Type1Name, "The type name wasn't changed."); }
public void Test_GetReferences() { EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences(); Assert.IsNotNull(references); Assert.AreEqual(0, references.Count, "Invalid number of references found before creating one."); TestUser user = new TestUser(); Guid userID = user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); Guid roleID = role.ID = Guid.NewGuid(); role.Name = "Test Role"; user.Roles = Collection <TestRole> .Add(user.Roles, role); DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); references = DataAccess.Data.Referencer.GetReferences(); Assert.IsNotNull(references); Assert.AreEqual(1, references.Count, "Invalid number of references found after creating one."); }
public void Test_CreateFilePath_Reference() { TestUser user = new TestUser(); user.FirstName = "First"; user.ID = Guid.NewGuid(); TestRole role = new TestRole(); role.ID = Guid.NewGuid(); user.Roles = new TestRole[] { role }; string basePath = TestUtilities.GetTestingPath(this) + Path.DirectorySeparatorChar + "Export"; EntityReference reference = DataAccess.Data.Referencer.GetActiveReferences(user)[0]; string path = new EntityFileNamer(reference, basePath).CreateFilePath(); string expected = basePath + Path.DirectorySeparatorChar + role.ShortTypeName + "-" + user.ShortTypeName + Path.DirectorySeparatorChar + reference.ID.ToString() + ".xml"; Assert.AreEqual(expected, path, "The path doesn't match what's expected."); }
public async void GetRolesAsync() { using (connection.BeginTransaction()) { // Arrange connection.UpdateIdentityRoleSchema <int, TestUser, TestRole>(); var userStore = CreateUserStore(); var user = new TestUser { UserName = "******" }; await userStore.CreateAsync(user); var roleStore = new RoleStore <TestRole, int>(connection); var role = new TestRole { Name = "Role" }; await roleStore.CreateAsync(role); await userStore.AddToRoleAsync(user, role.Name); // Act IList <string> result = await userStore.GetRolesAsync(user); // Assert Assert.Equal(role.Name, result[0]); } }
public void Test_GetReferences_Basic() { using (LogGroup logGroup = LogGroup.Start("Testing the retrieval of references for an entity.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); Guid userID = user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); Guid roleID = role.ID = Guid.NewGuid(); role.Name = "Test Role"; user.Roles = Collection <TestRole> .Add(user.Roles, role); DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences(user.GetType(), user.ID, "Roles", typeof(TestRole), false); Assert.IsNotNull(references, "The references object returned was null."); if (references != null) { Assert.AreEqual(1, references.Count, "Wrong number of references returned."); Assert.IsTrue(references[0].Includes(userID, "Roles"), "The user ID wasn't found on the reference."); Assert.IsTrue(references[0].Includes(roleID, "Users"), "The role ID wasn't found on the reference."); } } }
public async Task CreateRole() { // Create a session and role store for this test. var session = SessionFactory.OpenSession(); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role. var role = new TestRole { Name = "CreateRoleTest" }; using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); transaction.Commit(); } // Check the role has an id. Assert.IsNotNull(role.Id); // Create a new session and role store for this test, so that we actually hit the database and not the cache. roleStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); roleStore = new TestRoleStore<TestRole>(session); // Load the role. TestRole loadRole; using (var transaction = session.BeginTransaction()) { loadRole = await roleStore.FindByIdAsync(role.Id); transaction.Commit(); } // Check we have the same role. Assert.AreEqual(role.Id, loadRole.Id); Assert.AreEqual(role.Name, loadRole.Name); }
public virtual void Test_GetPageOfEntitiesWithReference_EmptyReferencedEntityID_NotFound() { using (LogGroup logGroup = LogGroup.Start("Testing the index retrieval of entities that don't have any references on a particular property.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); Guid userID = user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); Guid roleID = role.ID = Guid.NewGuid(); role.Name = "Test Role"; // Assign a user to the role role.Users = new TestUser[] { user }; DataAccess.Data.Saver.Save(user); DataAccess.Data.Saver.Save(role); PagingLocation location = new PagingLocation(0, 10); string sortExpression = "UsernameAscending"; TestRole[] foundRoles = DataAccess.Data.Indexer.GetPageOfEntitiesWithReference <TestRole>("Users", typeof(TestUser), Guid.Empty, location, sortExpression); Assert.IsNotNull(foundRoles, "The found roles object returned was null."); Assert.AreEqual(0, foundRoles.Length, "Invalid number of roles found."); } }
public void MPT_ORM_ForeignKey() { using (RF.TransactionScope(UnitTestEntityRepositoryDataProvider.DbSettingName)) { var repo = RF.ResolveInstance <TestUserRepository>(); var user = repo.New().CastTo <TestUser>(); user.Name = "huqf"; //为用户添加一个角色 var userRoles = user.TestRoleList; var role = new TestRole(); userRoles.Add(role); role.Name = "admin"; Assert.IsTrue(user.Id == role.TestUserId); Assert.IsTrue(!(user as IEntityWithId).IdProvider.IsAvailable(user.Id)); //保存新建用户 repo.Save(user); Assert.AreEqual(user.Id, role.TestUserId); var roles = RF.ResolveInstance <TestRoleRepository>().GetByUserId(user.Id); Assert.AreEqual(roles.Count, 1); Assert.AreEqual(userRoles.Count, 1); Assert.AreEqual(roles[0].CastTo <TestRole>().Name, role.Name); } }
public virtual void Test_Delete_RemoveReferences() { using (LogGroup logGroup = LogGroup.StartDebug("Testing saving of an EntityReference.")) { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "Test role"; // This should remain commented out to check for exclusion user.Roles = new TestRole[] { role }; DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); DataAccess.Data.Deleter.Delete(role); TestUser user2 = DataAccess.Data.Reader.GetEntity <TestUser>("ID", user.ID); DataAccess.Data.Activator.Activate(user2, "Roles"); Assert.IsNotNull(user2.Roles); if (user2.Roles != null) { Assert.AreEqual(0, user2.Roles.Length, "Incorrect number of roles. The role should have been removed."); } } }
private static TestContext CreateContext() { var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var services = new ServiceCollection(); var user = new TestUser { Username = "******", Discriminator = "0001" }; var channel = new TestGuildTextChannel { Name = "general" }; var role = new TestRole(); var guild = new TestGuild { Channels = { channel }, Roles = { role } }; var guildUser = guild.AddMember(user); var data = new TestBotData { Users = { user }, Guilds = { guild } }; services.AddLocalizations(); services.AddCommand(builder => { builder.AddModule <FooModule>(); }); services.AddCommandEfCoreRepositories <TestDbContext>(); services.AddSingleton <IMessageContextAccessor, MessageContextAccessor>(); services.AddDbContext <TestDbContext>(builder => { builder.UseSqlite(connection); }); var provider = services.BuildTestServiceProvider(data); provider.GetRequiredService <TestDbContext>().Database.EnsureCreated(); return(new TestContext(connection) { PermissionManager = provider.GetRequiredService <IPermissionManager>(), Guild = guild, Channel = channel, User = guildUser, Role = role }); }
public async Task IsInRoleReturnsTrueWhenAUserIsInARoleAndFalseWhenTheyAreNot() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore(session); var roleStore = new TestRoleStore(session); // Create and save a role and a user and add the role to the user. int numberOfOtherRoles = 3; string roleName = "IsInRoleTestRole"; var role = new TestRole(roleName); var user = new TestUser("IsInRoleTestUser"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); await userStore.AddToRoleAsync(user, role.Name); for (int i = 0; i < numberOfOtherRoles; i++) { var otherRole = new TestRole(roleName + i); await roleStore.CreateAsync(otherRole); await userStore.AddToRoleAsync(user, otherRole.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and that we get true when testing for the correct role and false for non-existent role. Assert.AreEqual(loadUser.Id, user.Id); bool inRole = await userStore.IsInRoleAsync(loadUser, roleName); bool notInRole = await userStore.IsInRoleAsync(loadUser, "NOTINROLETEST_USERNOTINROLE"); Assert.IsTrue(inRole); Assert.IsFalse(notInRole); }
public void MPT_ORM_PropertiesMapping_Inheritance() { var repo = RF.Find <TestAdministrator>() as TestUserRepository; //清空历史数据 var user = repo.GetByName("huqf"); if (user != null) { user.PersistenceStatus = PersistenceStatus.Deleted; repo.Save(user); } //新建用户并设置一些值。 var user1 = repo.New().CastTo <TestAdministrator>(); user1.Name = "huqf"; user1.Level = 1; TestUserExt.SetUserCode(user1, "NewUserCode"); //为用户添加一个角色 var userRoles = user1.TestRoleList; var role = new TestRole(); userRoles.Add(role); role.Name = "admin"; Assert.AreEqual(user1.Id, role.TestUserId); //保存新建用户 repo.Save(user1); //重新获取保存的用户 var user2 = repo.GetByName("huqf").CastTo <TestAdministrator>(); Assert.IsNotNull(user2); Assert.AreEqual(user1.Name, user2.Name); Assert.AreEqual(user2.Level, 1); Assert.AreEqual(TestUserExt.GetUserCode(user2), "NewUserCode"); Assert.AreEqual(user1.TestRoleList.Count, 1); Assert.AreEqual(user1.TestRoleList[0].CastTo <TestRole>().Name, "admin"); //获取 Role var role2 = RF.Find <TestRole>().GetById(role.Id).CastTo <TestRole>(); Assert.AreEqual(role.Name, "admin"); Assert.AreEqual(role2.Name, "admin"); Assert.AreEqual(user1.Id, role2.TestUserId); Assert.IsNotNull(role2.TestUser); //删除用户 user1.PersistenceStatus = PersistenceStatus.Deleted; repo.Save(user1); var users = repo.GetAll(); Assert.IsTrue(!users.Cast <TestUser>().Any(u => u.Name == "huqf")); }
public void Test_GetEntitiesByFilterGroup_EmptyGroup() { using (LogGroup logGroup = LogGroup.Start("Testing a simple query with the PropertyFilter.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; user.Username = "******"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "Test role"; user.Roles = new TestRole[] { role }; DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); ReferenceFilter filter = (ReferenceFilter)DataAccess.Data.CreateReferenceFilter(); filter.PropertyName = "Roles"; filter.ReferencedEntityID = role.ID; filter.ReferenceType = role.GetType(); filter.AddType(typeof(TestUser)); PropertyFilter filter2 = (PropertyFilter)DataAccess.Data.CreatePropertyFilter(); filter2.PropertyName = "Username"; filter2.PropertyValue = user.Username; filter2.AddType(typeof(TestUser)); FilterGroup filterGroup = new FilterGroup(); // Leave empty by not adding filters //filterGroup.Add(filter); //filterGroup.Add(filter2); IEntity[] found = (IEntity[])DataAccess.Data.Indexer.GetEntities(filterGroup); Assert.IsNotNull(found, "Null value returned"); if (found != null) { Assert.IsTrue(found.Length > 0, "No results found."); if (found.Length > 0) { TestUser foundUser = (TestUser)found[0]; Assert.IsNotNull(foundUser, "foundUser == null"); Assert.AreEqual(user.ID, foundUser.ID, "The IDs don't match."); } } } }
public virtual void Test_Update() { using (LogGroup logGroup = LogGroup.Start("Testing the DataAccess.Data.Updater.Update function.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); Guid userID = user.ID; user.FirstName = "Test-Before"; user.LastName = "User"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); Guid roleID = role.ID; role.Name = "Test Role"; user.Roles = new TestRole[] { role }; DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); TestUser user2 = (TestUser)DataAccess.Data.Reader.GetEntity(typeof(TestUser), "ID", user.ID); Assert.IsNotNull(user2, "user2 == null"); Assert.AreEqual(user.FirstName, user2.FirstName, "The name doesn't appear to have been saved."); DataAccess.Data.Activator.Activate(user2); user2.FirstName = "Test-Updated"; //user2.Roles.RemoveAt(0); DataAccess.Data.Updater.Update(user2); // TODO: Check if its possible to remove and dispose the store, then have it automatically reload when needed //store.Dispose(); //DataAccess.Data.Stores.Remove(store); TestUser user3 = (TestUser)DataAccess.Data.Reader.GetEntity <TestUser>("ID", user2.ID); Assert.IsNotNull(user3, "user3 == null"); Assert.AreEqual(user2.ID, user3.ID, "The IDs don't match."); Assert.AreEqual(user2.FirstName, user3.FirstName, "The name doesn't appear to have been updated."); //Assert.IsNotNull(toDelete, "The toDelete list is null."); //if (toDelete != null) // Assert.AreEqual(1, toDelete.Length, "Incorrect number of entities in toDelete list. Expecting the obsolete reference to be in the list."); } }
public void Test_GetReferences_2References() { using (LogGroup logGroup = LogGroup.Start("Testing the retrieval of references for an entity.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); Guid userID = user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); Guid roleID = role.ID = Guid.NewGuid(); role.Name = "Test Role"; TestRole role2 = new TestRole(); Guid role2ID = role2.ID = Guid.NewGuid(); role2.Name = "Test Role 2 "; user.Roles = new TestRole[] { role, role2 }; DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(role2); DataAccess.Data.Saver.Save(user); EntityReferenceCollection referenceEntities = DataAccess.Data.Referencer.GetReferences("TestUser", "TestRole"); Assert.AreEqual(2, referenceEntities.Count, "Incorrect number of references found in the store after saving entities."); EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences(user.GetType(), user.ID, "Roles", typeof(TestRole), false); Assert.IsNotNull(references, "The references object returned was null."); if (references != null) { Assert.AreEqual(2, references.Count, "Wrong number of references returned."); EntityReference reference1 = references[0]; EntityReference reference2 = references[1]; // Switch the references around if necessary to match (so they can be found in any order) if (!reference1.Includes(role.ID, "Users")) { EntityReference tmp = reference1; reference1 = reference2; reference2 = tmp; } Assert.IsTrue(reference1.Includes(userID, "Roles"), "The user ID wasn't found on the reference."); Assert.IsTrue(reference1.Includes(roleID, "Users"), "The role ID wasn't found on the reference."); Assert.IsTrue(reference2.Includes(userID, "Roles"), "The user ID wasn't found on the second reference."); Assert.IsTrue(reference2.Includes(role2ID, "Users"), "The role2 ID wasn't found on the second reference."); } } }
private static TestContext CreateContext() { var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var services = new ServiceCollection(); var channel = new TestGuildTextChannel { Name = "general" }; var role = new TestRole(); var guild = new TestGuild { Channels = { channel }, Roles = { role } }; var data = new TestBotData { Guilds = { guild } }; services.AddLocalizations(); services.AddCommandEfCoreRepositories <TestDbContext>(); services.AddSingleton <IMessageContextAccessor, MessageContextAccessor>(); services.AddCommand(builder => { builder.AddModule <FooModule>(); builder.AddModule <CoreModule>(); builder.AddModule <DefaultModule>(); }); services.AddDbContext <TestDbContext>(builder => { builder.UseSqlite(connection); }); var provider = services.BuildTestServiceProvider(data); provider.GetRequiredService <TestDbContext>().Database.EnsureCreated(); return(new TestContext(connection) { ModuleManager = provider.GetRequiredService <IModuleManager>(), Channel = channel, Guild = guild }); }
public void Test_LoadEntitiesFileList() { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "Test"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "Test Role"; TestArticle article = new TestArticle(); article.ID = Guid.NewGuid(); article.Title = "Test"; TestCategory category = new TestCategory(); category.ID = Guid.NewGuid(); category.Name = "Test"; user.Roles = new TestRole[] { role }; DataExporter exporter = (DataExporter)DataAccess.Data.InitializeDataExporter(); exporter.ExportDirectoryPath = TestUtilities.GetTestingPath(this) + Path.DirectorySeparatorChar + "Exported"; // IMPORTANT: Export the references before the entities, because the references are stripped from the entities upon export // Alternative is to reactivate the entities and their references using DataAccess.Data.Activator. EntityReferenceCollection references = DataAccess.Data.Referencer.GetActiveReferences(user); exporter.ExportEntity(references[0]); exporter.ExportEntity(user); exporter.ExportEntity(role); exporter.ExportEntity(article); exporter.ExportEntity(category); DataImporter importer = (DataImporter)DataAccess.Data.InitializeDataImporter(); importer.ImportableDirectoryPath = exporter.ExportDirectoryPath; string[] fileList = importer.LoadEntitiesFileList(); Assert.AreEqual(5, fileList.Length, "Incorrect number of files found."); }
public async Task AddRoleToUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore(session); var roleStore = new TestRoleStore(session); // Create and save a role and a user. string roleName = "AddRoleToUserTestRole"; var role = new TestRole(roleName); var user = new TestUser("AddRoleToUserTestUser"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); transaction.Commit(); } // Check the user has an Id and no roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, 0); var userId = user.Id; // Add the user to the role. using (var transaction = session.BeginTransaction()) { await userStore.AddToRoleAsync(user, role.Name); transaction.Commit(); } // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNotNull(userRole); }
public virtual void Test_Update_MaintainReferences() { using (LogGroup logGroup = LogGroup.Start("Testing the update function to see if it maintains references.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.LastName = "User"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); role.Name = "Test role"; // This should remain commented out to check for exclusion user.Roles = new TestRole[] { role }; DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); EntityReference reference = new EntityReference(); reference.ID = Guid.NewGuid(); reference.Type1Name = "TestUser"; reference.Type2Name = "TestRole"; reference.Entity1ID = user.ID; reference.Entity2ID = role.ID; reference.Property1Name = "Roles"; reference.Property2Name = "Users"; TestUser user2 = DataAccess.Data.Reader.GetEntity <TestUser>("ID", user.ID); DataAccess.Data.Activator.Activate(user2); string newFirstName = "Something else"; user2.FirstName = newFirstName; DataAccess.Data.Updater.Update(user2); TestUser user3 = DataAccess.Data.Reader.GetEntity <TestUser>("ID", user.ID); DataAccess.Data.Activator.Activate(user3); Assert.IsNotNull(user3.Roles); Assert.AreEqual(newFirstName, user3.FirstName, "First name mismatch."); if (user3.Roles != null) { Assert.AreEqual(1, user3.Roles.Length, "Incorrect number of roles."); } } }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator<TestRole>(); var manager = new RoleManager<TestRole>(new NoopRoleStore(), validator); var user = new TestRole {Name = input}; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, "Name cannot be null or empty."); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator<TestRole>(); var manager = MockHelpers.TestRoleManager<TestRole>(); var user = new TestRole {Name = input}; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, IdentityErrorDescriber.Default.InvalidRoleName(input)); }
public void Can_ReturnTrue() { // Arrange var role = new TestRole(); var sut = new RolePermissions(new List <Role> { role }); // Act var result = sut.Can(UserRoles.MedicalExaminer, Permission.AddEventToExamination); // Assert result.Should().BeTrue(); }
public async Task GetRolesForAUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore(session); var roleStore = new TestRoleStore(session); // Create and save a user and some roles and add the roles to the user. int numberOfRoles = 5; string roleName = "GetRolesForAUserTestRole"; var user = new TestUser("GetRolesForAUser"); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); for (int i = 0; i < numberOfRoles; i++) { var role = new TestRole(roleName + i); await roleStore.CreateAsync(role); await userStore.AddToRoleAsync(user, role.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfRoles); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore(session); // Load the user. TestUser loadUser; IList <string> roles; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); roles = await userStore.GetRolesAsync(user); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(roles.Count, numberOfRoles); }
public void Can_ReturnFalse_WhenException() { // Arrange var role = new TestRole(); var sut = new RolePermissions(new List <Role> { role }); // Act var result = sut.Can(UserRoles.MedicalExaminerOfficer, Permission.CreateUserPermission); // Assert result.Should().BeFalse(); }
public void PermissionsForRoles() { // Arrange var role = new TestRole(); var sut = new RolePermissions(new List <Role> { role }); // Act var result = sut.PermissionsForRoles(new[] { UserRoles.MedicalExaminer }); // Assert result.Keys.Should().Contain(Permission.AddEventToExamination); result[Permission.AddEventToExamination].Should().BeTrue(); }
public async Task ValidateFailsWithTooShortRoleName(string input) { // Setup var validator = new RoleValidator <TestRole>(); var manager = MockHelpers.TestRoleManager <TestRole>(); var user = new TestRole { Name = input }; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().InvalidRoleName(input)); }
public async Task UpdateRole() { // Create a session and role store for this test. var session = SessionFactory.OpenSession(); var roleStore = new TestRoleStore(session); // Create and save a role. string originalRoleName = "UpdateRoleTest"; string newRoleName = "NewUpdateRoleTest"; var role = new TestRole { Name = originalRoleName }; using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); transaction.Commit(); } // Check the role has an id and a name is correct. Assert.IsNotNull(role.Id); Assert.AreEqual(role.Name, originalRoleName); // Change the role name. using (var transaction = session.BeginTransaction()) { role.Name = newRoleName; await roleStore.UpdateAsync(role); transaction.Commit(); } // Create a new session and role store so that we actually hit the database and not the cache. roleStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); roleStore = new TestRoleStore(session); // Load the updated the role. TestRole updatedRole; using (var transaction = session.BeginTransaction()) { updatedRole = await roleStore.FindByIdAsync(role.Id); transaction.Commit(); } // Check the role name has been updated and saved. Assert.AreEqual(updatedRole.Name, newRoleName); }
public void Test_GetActiveReferences_Multiple_Sync() { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); TestRole role = new TestRole(); role.ID = Guid.NewGuid(); TestRole role2 = new TestRole(); role2.ID = Guid.NewGuid(); user.Roles = new TestRole[] { role, role2 }; EntityReferenceCollection references = DataAccess.Data.Referencer.GetActiveReferences(user); Assert.IsNotNull(references, "The reference collection is null."); Assert.AreEqual(2, references.Count, "Incorrect number of references returned."); if (references != null && references.Count == 2) { EntityReference reference = references[0]; Assert.AreEqual(user.ID, references[0].Entity1ID, "The entity 1 ID wasn't set correctly."); Assert.AreEqual(role.ID, references[0].Entity2ID, "The entity 2 ID wasn't set correctly."); Assert.AreEqual("TestUser", references[0].Type1Name, "The type name 1 wasn't set correctly."); Assert.AreEqual("TestRole", references[0].Type2Name, "The type name 2 wasn't set correctly."); Assert.AreEqual("Roles", references[0].Property1Name, "The property 1 name wasn't set correctly."); Assert.AreEqual("Users", references[0].Property2Name, "The property 2 name wasn't set correctly."); EntityReference reference2 = references[1]; Assert.AreEqual(user.ID, reference2.Entity1ID, "The entity 1 ID wasn't set correctly."); Assert.AreEqual(role2.ID, reference2.Entity2ID, "The entity 2 ID wasn't set correctly."); Assert.AreEqual("TestUser", reference2.Type1Name, "The type name 1 wasn't set correctly."); Assert.AreEqual("TestRole", reference2.Type2Name, "The type name 2 wasn't set correctly."); Assert.AreEqual("Roles", reference2.Property1Name, "The property 1 name wasn't set correctly."); Assert.AreEqual("Users", reference2.Property2Name, "The property 2 name wasn't set correctly."); } }
public virtual void Test_Update_RemoveObsoleteReference_Sync() { using (LogGroup logGroup = LogGroup.Start("Testing the DataAccess.Data.Updater.Update function to ensure obsolete references are removed.", NLog.LogLevel.Debug)) { TestUser user = new TestUser(); user.ID = Guid.NewGuid(); Guid userID = user.ID; user.FirstName = "Test-Before"; user.LastName = "User"; TestRole role = new TestRole(); role.ID = Guid.NewGuid(); Guid roleID = role.ID; role.Name = "Test Role"; user.Roles = new TestRole[] { role }; // Save the user and the role with a reference between them DataAccess.Data.Saver.Save(role); DataAccess.Data.Saver.Save(user); TestUser user2 = (TestUser)DataAccess.Data.Reader.GetEntity(typeof(TestUser), "ID", user.ID); Assert.IsNotNull(user2, "user2 == null"); Assert.AreEqual(user.FirstName, user2.FirstName, "The name doesn't appear to have been saved."); DataAccess.Data.Activator.Activate(user2); // Clear the roles from the user user2.Roles = new TestRole[] {}; // Update the user which should remove the obsolete reference DataAccess.Data.Updater.Update(user2); TestUser user3 = (TestUser)DataAccess.Data.Reader.GetEntity <TestUser>("ID", user2.ID); Assert.IsNotNull(user3, "user3 == null"); Assert.AreEqual(user2.ID, user3.ID, "The IDs don't match."); EntityReferenceCollection references = DataAccess.Data.Referencer.GetReferences("TestUser", "TestRole"); Assert.AreEqual(0, references.Count, "Invalid number of references found."); } }
public void GetPropertyValueTest() { // Arrange. var typeResolver = Mock.Create<ITypeResolver>(Behavior.Loose); var role1 = new TestRole { Name = "Test Role 1" }; var role2 = new TestRole { Name = "Test Role 2", ParentRole = new TestRole { Name = "Parent Role" } }; var businessUnit = new TestBusinessUnit { Name = "Test BU", ParentBusinessUnit = new TestBusinessUnit { Name = "Parent BU" } }; var employee = new TestEmployee { FirstName = "aaa", LastName = "AAA", BusinessUnit = businessUnit, Roles = new[] { role1, role2 } }; var request = new TestRequest1 { Employee = employee }; var context = new WebMethodResultDataContext(request, typeResolver); // Act / Assert. Assert.IsNull(context.GetPropertyValue(null)); Assert.AreEqual("aaa", context.GetPropertyValue("Employee|FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employee|LastName")); Assert.AreEqual("Test BU", context.GetPropertyValue("Employee|BusinessUnit|Name")); Assert.AreEqual("Parent BU", context.GetPropertyValue("Employee|BusinessUnit|ParentBusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employee|Roles|Name")); Assert.IsNull(context.GetPropertyValue("Employee|Roles|ParentRole|Name")); }
public bool Contains(TestRole entity) { return base.Contains(entity); }
public void Add(TestRole entity) { base.Add(entity); }
public bool Remove(TestRole entity) { return base.Remove(entity); }
public void Insert(int index, TestRole entity) { base.Insert(index, entity); }
public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims) { // Setup var userManager = MockHelpers.MockUserManager<TestUser>(); var roleManager = MockHelpers.MockRoleManager<TestRole>(); var user = new TestUser { UserName = "******" }; userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims); userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles); userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id); userManager.Setup(m => m.GetUserNameAsync(user)).ReturnsAsync(user.UserName); var roleClaims = new[] { "Admin", "Local" }; if (supportRoles) { userManager.Setup(m => m.GetRolesAsync(user)).ReturnsAsync(roleClaims); roleManager.Setup(m => m.SupportsRoleClaims).Returns(supportRoleClaims); } var userClaims = new[] { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") }; if (supportClaims) { userManager.Setup(m => m.GetClaimsAsync(user)).ReturnsAsync(userClaims); } userManager.Object.Options = new IdentityOptions(); var admin = new TestRole() { Name = "Admin" }; var local = new TestRole() { Name = "Local" }; var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") }; var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") }; if (supportRoleClaims) { roleManager.Setup(m => m.FindByNameAsync("Admin")).ReturnsAsync(admin); roleManager.Setup(m => m.FindByNameAsync("Local")).ReturnsAsync(local); roleManager.Setup(m => m.GetClaimsAsync(admin)).ReturnsAsync(adminClaims); roleManager.Setup(m => m.GetClaimsAsync(local)).ReturnsAsync(localClaims); } var options = new Mock<IOptions<IdentityOptions>>(); var identityOptions = new IdentityOptions(); options.Setup(a => a.Options).Returns(identityOptions); var factory = new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager.Object, roleManager.Object, options.Object); // Act var principal = await factory.CreateAsync(user); var identity = principal.Identities.First(); // Assert var manager = userManager.Object; Assert.NotNull(identity); Assert.Equal(1, principal.Identities.Count()); Assert.Equal(IdentityOptions.ApplicationCookieAuthenticationType, identity.AuthenticationType); var claims = identity.Claims.ToList(); Assert.NotNull(claims); Assert.True( claims.Any(c => c.Type == manager.Options.ClaimsIdentity.UserNameClaimType && c.Value == user.UserName)); Assert.True(claims.Any(c => c.Type == manager.Options.ClaimsIdentity.UserIdClaimType && c.Value == user.Id)); Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Admin")); Assert.Equal(supportRoles, claims.Any(c => c.Type == manager.Options.ClaimsIdentity.RoleClaimType && c.Value == "Local")); foreach (var cl in userClaims) { Assert.Equal(supportClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } foreach (var cl in adminClaims) { Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } foreach (var cl in localClaims) { Assert.Equal(supportRoleClaims, claims.Any(c => c.Type == cl.Type && c.Value == cl.Value)); } userManager.VerifyAll(); roleManager.VerifyAll(); }
public void ET_Property_Enum_ForUI() { var entity = new TestRole { RoleType = RoleType.Administrator }; var properties = (entity as ICustomTypeDescriptor).GetProperties(); var enumProperty = properties.Find("RoleType", false); Assert.IsNotNull(enumProperty, "TestRole 类型上没有找到 RoleType 枚举属性。"); Assert.IsTrue(enumProperty.PropertyType == typeof(string), "枚举属性在界面的返回值类型应该是字符串。"); var value = enumProperty.GetValue(entity) as string; Assert.IsTrue(value != null && value == "管理员", "枚举属性在界面的返回值应该是枚举在 Label 标签中定义的字符串。"); enumProperty.SetValue(entity, "一般"); Assert.IsTrue(entity.RoleType == RoleType.Normal, "枚举属性被界面设置字符串的值时,应该转换为相应的枚举值。"); }
public void EnumerateItemsTest() { // Arrange. var editItem = new TestEdit(); var employee1 = new TestEmployee { FirstName = "aaa", LastName = "AAA", BusinessUnit = 11, BusinessUnitMember = new TestBusinessUnit { Name = "BU 1" } }; var employee2 = new TestEmployee { FirstName = "bbb", LastName = "BBB", BusinessUnit = 12, BusinessUnitMember = new TestBusinessUnit { Name = "BU 2" } }; var employeesRetriever = new Mock<IProcessFieldItemsRetriever>(); employeesRetriever.Setup(x => x.ItemType).Returns(typeof(TestEmployee)); employeesRetriever.Setup(x => x.GetItems(editItem)).Returns(new[] { employee1, employee2 }); var role1 = new TestRole { Name = "Role 1" }; var role2 = new TestRole { Name = "Role 2" }; var role3 = new TestRole { Name = "Role 3" }; var rolesRetriever = new Mock<IProcessFieldItemsRetriever>(); rolesRetriever.Setup(x => x.ItemType).Returns(typeof(TestRole)); rolesRetriever.Setup(x => x.GetItems(employee1)).Returns(new[] { role1 }); rolesRetriever.Setup(x => x.GetItems(employee2)).Returns(new[] { role2, role3 }); var retrieverFactory = new Mock<IProcessFieldItemsRetrieverFactory>(); retrieverFactory.Setup(x => x.CreateItemsRetriever(typeof(TestEdit), "Employees")).Returns(employeesRetriever.Object); retrieverFactory.Setup(x => x.CreateItemsRetriever(typeof(TestEmployee), "Roles")).Returns(rolesRetriever.Object); var context = new EditableRootDataContext(editItem, retrieverFactory.Object); // Act / Assert. var employees = context.EnumerateItems("Employees"); var employeeEnumerator = employees.GetEnumerator(); Assert.IsNull(context.GetPropertyValue("Employees.FirstName")); Assert.IsNull(context.GetPropertyValue("Employees.LastName")); Assert.IsNull(context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.IsNull(context.GetPropertyValue("Employees.Roles.Name")); Assert.IsTrue(employeeEnumerator.MoveNext()); Assert.AreEqual("aaa", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 1", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.IsNull(context.GetPropertyValue("Employees.Roles.Name")); var roles = context.EnumerateItems("Employees.Roles"); var rolesEnumerator = roles.GetEnumerator(); Assert.IsTrue(rolesEnumerator.MoveNext()); Assert.AreEqual("aaa", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 1", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.AreEqual("Role 1", context.GetPropertyValue("Employees.Roles.Name")); Assert.IsFalse(rolesEnumerator.MoveNext()); Assert.AreEqual("aaa", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 1", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.IsNull(context.GetPropertyValue("Employees.Roles.Name")); Assert.IsTrue(employeeEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.IsNull(context.GetPropertyValue("Employees.Roles.Name")); roles = context.EnumerateItems("Employees.Roles"); rolesEnumerator = roles.GetEnumerator(); Assert.IsTrue(rolesEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.AreEqual("Role 2", context.GetPropertyValue("Employees.Roles.Name")); Assert.IsTrue(rolesEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.AreEqual("Role 3", context.GetPropertyValue("Employees.Roles.Name")); Assert.IsFalse(rolesEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees.FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees.LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.IsNull(context.GetPropertyValue("Employees.Roles.Name")); Assert.IsFalse(employeeEnumerator.MoveNext()); Assert.IsNull(context.GetPropertyValue("Employees.FirstName")); Assert.IsNull(context.GetPropertyValue("Employees.LastName")); Assert.IsNull(context.GetPropertyValue("Employees.BusinessUnit.Name")); Assert.IsNull(context.GetPropertyValue("Employees.Roles.Name")); }
public async Task RemoveRoleFromUserOnlyRemovesSingleRole() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role and a user and add the role to the user. int numberOfOtherRoles = 3; string roleName = "RemoveRoleFromUserOnlyRemovesSingleRole"; var role = new TestRole(roleName); var user = new TestUser("RemoveRoleFromUserOnlyRemovesSingleRole"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); await userStore.AddToRoleAsync(user, role.Name); for (int i = 0; i < numberOfOtherRoles; i++) { var otherRole = new TestRole(roleName + i); await roleStore.CreateAsync(otherRole); await userStore.AddToRoleAsync(user, otherRole.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNotNull(userRole); // Now remove the role. using (var transaction = session.BeginTransaction()) { await userStore.RemoveFromRoleAsync(loadUser, roleName); transaction.Commit(); } // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user again. using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and the role has been removed. Assert.AreEqual(loadUser.Id, user.Id); userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNull(userRole); }
public async Task IsInRoleReturnsTrueWhenAUserIsInARoleAndFalseWhenTheyAreNot() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role and a user and add the role to the user. int numberOfOtherRoles = 3; string roleName = "IsInRoleTestRole"; var role = new TestRole(roleName); var user = new TestUser("IsInRoleTestUser"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); await userStore.AddToRoleAsync(user, role.Name); for (int i = 0; i < numberOfOtherRoles; i++) { var otherRole = new TestRole(roleName + i); await roleStore.CreateAsync(otherRole); await userStore.AddToRoleAsync(user, otherRole.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and that we get true when testing for the correct role and false for non-existent role. Assert.AreEqual(loadUser.Id, user.Id); bool inRole = await userStore.IsInRoleAsync(loadUser, roleName); bool notInRole = await userStore.IsInRoleAsync(loadUser, "NOTINROLETEST_USERNOTINROLE"); Assert.IsTrue(inRole); Assert.IsFalse(notInRole); }
public async Task DeleteRole() { // Create a session and role store for this test. var session = SessionFactory.OpenSession(); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role. string userName = "******"; var role = new TestRole { Name = userName }; using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); transaction.Commit(); } // Check the role has an id and a name. Assert.IsNotNull(role.Id); Assert.IsNotNull(role.Name); var roleId = role.Id; // Create a new session and role store so that we actually hit the database and not the cache. roleStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); roleStore = new TestRoleStore<TestRole>(session); // Load and delete the role. using (var transaction = session.BeginTransaction()) { role = await roleStore.FindByIdAsync(roleId); await roleStore.DeleteAsync(role); transaction.Commit(); } // Check that the role has been deleted. var deletedUser = await roleStore.FindByIdAsync(roleId); Assert.IsNull(deletedUser); }
public async Task UpdateRole() { // Create a session and role store for this test. var session = SessionFactory.OpenSession(); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role. string originalRoleName = "UpdateRoleTest"; string newRoleName = "NewUpdateRoleTest"; var role = new TestRole { Name = originalRoleName }; using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); transaction.Commit(); } // Check the role has an id and a name is correct. Assert.IsNotNull(role.Id); Assert.AreEqual(role.Name, originalRoleName); // Change the role name. using (var transaction = session.BeginTransaction()) { role.Name = newRoleName; await roleStore.UpdateAsync(role); transaction.Commit(); } // Create a new session and role store so that we actually hit the database and not the cache. roleStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); roleStore = new TestRoleStore<TestRole>(session); // Load the updated the role. TestRole updatedRole; using (var transaction = session.BeginTransaction()) { updatedRole = await roleStore.FindByIdAsync(role.Id); transaction.Commit(); } // Check the role name has been updated and saved. Assert.AreEqual(updatedRole.Name, newRoleName); }
public int IndexOf(TestRole entity) { return base.IndexOf(entity); }
public async Task AddRoleToUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role and a user. string roleName = "AddRoleToUserTestRole"; var role = new TestRole(roleName); var user = new TestUser("AddRoleToUserTestUser"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); transaction.Commit(); } // Check the user has an Id and no roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, 0); var userId = user.Id; // Add the user to the role. using (var transaction = session.BeginTransaction()) { await userStore.AddToRoleAsync(user, role.Name); transaction.Commit(); } // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNotNull(userRole); }
public void EnumerateItemsTest() { // Arrange. var typeResolver = Mock.Create<ITypeResolver>(Behavior.Loose); var role1 = new TestRole { Name = "Role 1" }; var role2 = new TestRole { Name = "Role 2" }; var role3 = new TestRole { Name = "Role 3" }; var businessUnit1 = new TestBusinessUnit { Name = "BU 1" }; var businessUnit2 = new TestBusinessUnit { Name = "BU 2" }; var employee1 = new TestEmployee { FirstName = "aaa", LastName = "AAA", BusinessUnit = businessUnit1, Roles = new[] { role1 } }; var employee2 = new TestEmployee { FirstName = "bbb", LastName = "BBB", BusinessUnit = businessUnit2, Roles = new[] { role2, role3 } }; var request = new TestRequest2 { Employees = new[] { employee1, employee2 } }; var context = new WebMethodResultDataContext(request, typeResolver); // Act / Assert. var employees = context.EnumerateItems("Employees"); var employeeEnumerator = employees.GetEnumerator(); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|LastName")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|Roles|Name")); Assert.IsTrue(employeeEnumerator.MoveNext()); Assert.AreEqual("aaa", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 1", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); var roles = context.EnumerateItems("Employees|Item[]|Roles"); var rolesEnumerator = roles.GetEnumerator(); Assert.IsTrue(rolesEnumerator.MoveNext()); Assert.AreEqual("aaa", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 1", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.AreEqual("Role 1", context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); Assert.IsFalse(rolesEnumerator.MoveNext()); Assert.AreEqual("aaa", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("AAA", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 1", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); Assert.IsTrue(employeeEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); roles = context.EnumerateItems("Employees|Item[]|Roles"); rolesEnumerator = roles.GetEnumerator(); Assert.IsTrue(rolesEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.AreEqual("Role 2", context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); Assert.IsTrue(rolesEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.AreEqual("Role 3", context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); Assert.IsFalse(rolesEnumerator.MoveNext()); Assert.AreEqual("bbb", context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.AreEqual("BBB", context.GetPropertyValue("Employees|Item[]|LastName")); Assert.AreEqual("BU 2", context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); Assert.IsFalse(employeeEnumerator.MoveNext()); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|FirstName")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|LastName")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|BusinessUnit|Name")); Assert.IsNull(context.GetPropertyValue("Employees|Item[]|Roles|Item[]|Name")); }
public async Task GetRolesForAUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a user and some roles and add the roles to the user. int numberOfRoles = 5; string roleName = "GetRolesForAUserTestRole"; var user = new TestUser("GetRolesForAUser"); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); for (int i = 0; i < numberOfRoles; i++) { var role = new TestRole(roleName + i); await roleStore.CreateAsync(role); await userStore.AddToRoleAsync(user, role.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfRoles); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; IList<string> roles; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); roles = await userStore.GetRolesAsync(user); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(roles.Count, numberOfRoles); }
public void ET_LazyRef_Serialization_OnServer() { var role = new TestRole { TestUser = new TestUser { Id = 1, Name = "TestUser" } }; Assert.IsTrue(TestRole.TestUserProperty.DefaultMeta.Serializable, "默认在服务端,应该是可以序列化实体的。"); var roleCloned = ObjectCloner.Clone(role); var loaded = roleCloned.FieldExists(TestRole.TestUserProperty); Assert.IsTrue(loaded, "服务端到客户端,需要序列化实体。"); }
public void ET_Property_Enum() { using (RF.TransactionScope(UnitTestEntityRepositoryDataProvider.DbSettingName)) { var user = new TestUser { Name = "DDDDD" }; RF.Save(user); var repo = RF.Concrete<TestRoleRepository>(); var entity = new TestRole { TestUser = user, RoleType = RoleType.Administrator }; repo.Save(entity); var entity2 = repo.GetById(entity.Id); Assert.AreEqual(entity.RoleType, entity2.RoleType); } }