Skip to content

Instantly share code, notes, and snippets.

@OliverUv
Created June 30, 2012 19:09
Show Gist options
  • Save OliverUv/3025129 to your computer and use it in GitHub Desktop.
Save OliverUv/3025129 to your computer and use it in GitHub Desktop.
from django.db import transaction
from django.http import HttpResponse
class RollbackAndReport(Exception):
def __init__(self, error_json_report):
self.error_json_report = error_json_report
def __str__(self):
return self.error_json_report
def reportable_commit_on_success(f):
@transaction.commit_manually
def decorated_function(*args, **kwargs):
try:
result = f(*args, **kwargs)
except RollbackAndReport as e:
transaction.rollback()
return HttpResponse(e.error_json_report)
except:
transaction.rollback()
raise
else:
try:
transaction.commit()
return result
except:
transaction.rollback()
raise
return decorated_function
def test_report_error(self):
@reportable_commit_on_success
def insert_user():
User(name='matri', pwd='boop', longname='Matthieu Ricard').save()
raise RollbackAndReport(json.dumps({'error': 'catch me if you can'}))
return HttpResponse(json.dumps({'should not': 'return this'}))
User.objects.all().delete()
response = insert_user()
parsed_response = json.loads(response.content)
expected_result = {'error': 'catch me if you can'}
self.assertEqual(response.status_code, 200)
self.assertEqual(expected_result, parsed_response)
self.assertEqual(0, User.objects.all().count())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment