Skip to content

Instantly share code, notes, and snippets.

@wolever
Created November 16, 2010 21:08
Show Gist options
  • Save wolever/702513 to your computer and use it in GitHub Desktop.
Save wolever/702513 to your computer and use it in GitHub Desktop.
Patch `objects.get` so its DoesNotExist errors are more helpful
from django.conf import settings
from django.core.management import call_command
from django.db import models as m
from django.db.models import loading
from ..patch_objects_get import patch_objects_get
@patch_objects_get
class PatchObjectsGetDecoratorModel(m.Model):
id = m.AutoField(primary_key=True)
class ModelTestBase(object):
""" Adds 'tests.modules' INSTALLED_APPS and runs syncdb. """
@classmethod
def syncdb(cls):
loading.cache.loaded = False
call_command('syncdb', verbosity=0)
@classmethod
def setup_class(cls):
cls.old_installed_apps = settings.INSTALLED_APPS
module = ".".join(__name__.split(".")[:-1])
settings.INSTALLED_APPS = (module, )
cls.syncdb()
@classmethod
def teardown_class(cls):
settings.INSTALLED_APPS = cls.old_installed_apps
cls.syncdb()
from functools import wraps
def patch_objects_get(cls):
""" Patch 'cls.objects.get' so its DoesNotExist errors will be more
helpful.
Usage:
>>> @patch_objects_get
... class MyModel(m.Model):
... pass
...
>>> class MyOtherModel(m.Model):
... pass
...
>>> patch_objects_get(MyOtherModel)
>>> MyModel.objects.get(id=3141)
Traceback (most recent call last):
...
DoesNotExist: MyModel matching {"id": 42} does not exist
>>> """
old_get = cls.objects.get
@wraps(cls.objects.get)
def get_wrapper(*args, **kwargs):
try:
return old_get(*args, **kwargs)
except cls.DoesNotExist, e:
e.args = ("%s matching %r does not exist"
%(cls.__name__, kwargs), )
raise e
cls.objects.get = get_wrapper
return cls
from nose.tools import assert_equal
from ..patch_objects_get import patch_objects_get
from . import models as m
class TestManagers(m.ModelTestBase):
def test_patch_objects_get(self):
try:
m.PatchObjectsGetDecoratorModel.objects.get(id=3141)
except m.PatchObjectsGetDecoratorModel.DoesNotExist, e:
assert "PatchObjectsGetDecoratorModel" in str(e)
assert "3141" in str(e)
else:
raise AssertionError("expected error not raised")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment