1

My code tests if the inputted email and username are the same and raises an error if they are not. I am trying to test the code and it should pass if an exception is raised but I get the exception but the test still fails. Code:

def is_valid_email(email, cognitoUsername):
    if email != cognitoUsername:
        print("User email invalid")
        raise Exception("Username and Email address must be the same")
    print("User email valid")
    return True

Test:

self.assertEqual(lambda_function.is_valid_email("[email protected]", "[email protected]"), True)
self.assertRaises(Exception, lambda_function.is_valid_email("[email protected]", "test"))

Error:


email = '[email protected]', cognitoUsername = 'test'

    def is_valid_email(email, cognitoUsername):
        if email != cognitoUsername:
            print("User email invalid")
>           raise Exception("Username and Email address must be the same")
E           Exception: Username and Email address must be the same

../lambda_function.py:32: Exception




============================== 1 failed in 0.53s ===============================

Process finished with exit code 1

1 Answer 1

2

Your test code should call assertRaises() with a callable:

self.assertRaises(Exception, lambda: lambda_function.is_valid_email("[email protected]", "test"))

The other option is to use with like this:

with self.assertRaises(Exception):
    lambda_function.is_valid_email("[email protected]", "test")
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! is it possible to only pass if the Exception has a message, Exception("Username and Email address must be the same")?
Have a look at this answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.