Search code examples
c#unit-testingpasswordsmembership-provider

Testing Password format


Ok I am writeing a test for a membership password change. The code below is what I have so far. I need some assistance to check the password format. Min char length is 7 and max length is 8.

Also the I can test if the password format is clear, but how do I test an encrypted format?

Can anyone assist?

    [TestMethod]
    public void TestChangePassword()
    {
        try      
        {
            AsaMembershipProvider prov = this.GetMembershipProvider();
            MembershipCreateStatus status;

            //creates user
            MembershipUser user = prov.CreateUser("testUserX", "12345", "test.UserX@abc.com", "", "", true, null, out status);

            //gets user
            user = prov.GetUser("testUserX", false); 
            Assert.AreEqual(user.UserName, "testUserX");

            //Authenticates username and password
            var isAuthenticated = prov.ValidateUser(user.UserName, "12345");
            Assert.IsTrue(isAuthenticated);


            //changes password
            prov.ChangePassword("testUserX",  "12345", "ABCDE");

            //Validates password has been changed
            prov.ValidateUser(user.UserName, "ABCDE");
            Assert.IsTrue(isAuthenticated);

            // Change password back
            prov.ChangePassword("testUserX", "ABCDE", "12345");

            //Validates password has been changed back
            prov.ValidateUser(user.UserName, "12345");


            //Deletes User
            prov.DeleteUser("testUserX", true);
            //tries to get user again
            user = prov.GetUser("testUserX", false);
            //test that no user is returned
            Assert.AreEqual(null, user);

        }
        catch (Exception ex)
        {
            LogMessage(ex);
            Assert.Fail(ex.Message);
        }

    }

Solution

  • One option would be to write an extension method targeting AsaMembershipProvider which would validate the password and then call ChangePassword from within it to do the actual change

    The downside of the approach is that you will have more code to maintain

    public static class CryptoExtensions {
    
        public static void ChangePasswordEx(this AsaMembershipProvider mp, string username, string oldPassword, string newPassword){
            // validate format of the password
            if (true /*validation code*/ )
            {
                throw new Exception("Invalid password format");
            }
    
            // rest of the code to encrypt and store the password
            mp.ChangePassword(username, oldPassword, newPassword);
        }
    
    }
    

    Your test code should now call prov.ChangePassword with prov.ChangePasswordEx