Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django testing commit_on_success

I have a function that I've got wrapped in @transaction.commit_on_success and running Django unit tests on it.

The function is too long to paste, but some pseudocode is:

@transaction.commit_on_success
def func():
  order = Order.create()
  order.save()
  OrderItem.create(order=order)
  test = 10/0 # make sure we run into an error

Then in my unit test I check if len(Order.objects.all()) == 0

My function is returning a valid Order object, so the transaction is committing.

What am I doing wrong here?

EDIT: I'm on Django 1.5

like image 738
grokpot Avatar asked Mar 15 '23 22:03

grokpot


1 Answers

Figured it out.

I need to use TransactionTestCase (no documentation for 1.5).

A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

I had run across this before but tried to use it in tandem with TestCase. They are mutually exclusive and your unit test can only use one or another. Because we are using a custom test class, I had to some manuvering, but everything is now rolling back properly.

It also looks like Django 1.8 TestCase now supports transaction testing:

In older versions of Django, the effects of transaction commit and rollback could not be tested within a TestCase. With the completion of the deprecation cycle of the old-style transaction management in Django 1.8, transaction management commands (e.g. transaction.commit()) are no longer disabled within TestCase.

Thank you to John and siracoj for your answers. It's probably best that I upgrade from 1.5 anyways ;)

like image 155
grokpot Avatar answered Mar 31 '23 05:03

grokpot