0

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("test@email.com", "test@email.com"), True)
self.assertRaises(Exception, lambda_function.is_valid_email("test@email.com", "test"))

Error:


email = 'test@email.com', 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
L44TXF
  • 65
  • 3
  • 10

1 Answers1

1

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

self.assertRaises(Exception, lambda: lambda_function.is_valid_email("test@email.com", "test"))

The other option is to use with like this:

with self.assertRaises(Exception):
    lambda_function.is_valid_email("test@email.com", "test")
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Thank you! is it possible to only pass if the Exception has a message, Exception("Username and Email address must be the same")? – L44TXF Aug 20 '21 at 09:05
  • Have a look at this [answer](https://stackoverflow.com/a/3166985) – quamrana Aug 20 '21 at 09:14