mardi 6 janvier 2015

Django/Python unittesting: How to Force Exception of Try/Except Block

Is there any way to force the except block to execute so that I can verify the error messages/handling with unit testing? For example:


views.py



def get_books(request):
...
try:
book = Books.objects.get_or_create(user=request.user)
except:
messages.error(request, 'Unable to create new book!')
return HttpResponseRedirect(reverse('my_books'))

# more try/except cases


So in this example, how can I simulate basically an ORM failure? Sure, I can try to send in an invalid user for this case, but is there a general way to throw exceptions using libraries? Mock for instance. Or is there some other method to use unittest to force exceptions? Obviously there are going to be many try/except blocks throughout the code, so I'm looking for any help.


Aucun commentaire:

Enregistrer un commentaire