简体   繁体   中英

Testing for exception fails

When I save a User model, I would like to check if it has a username. Therefore I wrote this pre_save :

@receiver(pre_save, sender=User)
def validate_user(sender, instance, **kwargs):
    if len(instance.username) <= 5: raise Exception("Username too short")

Now in my testing method I would like to test this exception:

def test_user_no_username(self):
    u = User.objects.create()
    self.assertRaises(Exception, u.save())

The test fails. Why?

assertRaises is kind of a specific exception - as a second argument you should pass a callable :

assertRaises(exception, callable, *args, **kwds)

In other words, don't call u.save() :

self.assertRaises(Exception, u.save)

Also, you should really think about having custom exceptions or using built-in Django validation errors instead of raising and catching the broad Exception .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM