Source

django-model-utils / model_utils / tests / tests.py

Full commit
from datetime import datetime, timedelta

from django.test import TestCase
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models.fields import FieldDoesNotExist

from model_utils import ChoiceEnum, Choices
from model_utils.fields import get_excerpt
from model_utils.managers import QueryManager
from model_utils.tests.models import (InheritParent, InheritChild, TimeStamp,
    Post, Article, Status, StatusPlainTuple, TimeFrame, Monitored,
    StatusManagerAdded, TimeFrameManagerAdded, Entry)


class GetExcerptTests(TestCase):
    def test_split(self):
        e = get_excerpt("some content\n\n<!-- split -->\n\nsome more")
        self.assertEquals(e, 'some content\n')

    def test_auto_split(self):
        e = get_excerpt("para one\n\npara two\n\npara three")
        self.assertEquals(e, 'para one\n\npara two')

    def test_middle_of_para(self):
        e = get_excerpt("some text\n<!-- split -->\nmore text")
        self.assertEquals(e, 'some text')

    def test_middle_of_line(self):
        e = get_excerpt("some text <!-- split --> more text")
        self.assertEquals(e, "some text <!-- split --> more text")
    
class SplitFieldTests(TestCase):
    full_text = u'summary\n\n<!-- split -->\n\nmore'
    excerpt = u'summary\n'
    
    def setUp(self):
        self.post = Article.objects.create(
            title='example post', body=self.full_text)

    def test_unicode_content(self):
        self.assertEquals(unicode(self.post.body), self.full_text)

    def test_excerpt(self):
        self.assertEquals(self.post.body.excerpt, self.excerpt)

    def test_content(self):
        self.assertEquals(self.post.body.content, self.full_text)

    def test_has_more(self):
        self.failUnless(self.post.body.has_more)

    def test_not_has_more(self):
        post = Article.objects.create(title='example 2',
                                      body='some text\n\nsome more\n')
        self.failIf(post.body.has_more)
        
    def test_load_back(self):
        post = Article.objects.get(pk=self.post.pk)
        self.assertEquals(post.body.content, self.post.body.content)
        self.assertEquals(post.body.excerpt, self.post.body.excerpt)

    def test_assign_to_body(self):
        new_text = u'different\n\n<!-- split -->\n\nother'
        self.post.body = new_text
        self.post.save()
        self.assertEquals(unicode(self.post.body), new_text)

    def test_assign_to_content(self):
        new_text = u'different\n\n<!-- split -->\n\nother'
        self.post.body.content = new_text
        self.post.save()
        self.assertEquals(unicode(self.post.body), new_text)

    def test_assign_to_excerpt(self):
        def _invalid_assignment():
            self.post.body.excerpt = 'this should fail'
        self.assertRaises(AttributeError, _invalid_assignment)


class MonitorFieldTests(TestCase):
    def setUp(self):
        self.instance = Monitored(name='Charlie')
        self.created = self.instance.name_changed

    def test_save_no_change(self):
        self.instance.save()
        self.assertEquals(self.instance.name_changed, self.created)

    def test_save_changed(self):
        self.instance.name = 'Maria'
        self.instance.save()
        self.failUnless(self.instance.name_changed > self.created)

    def test_double_save(self):
        self.instance.name = 'Jose'
        self.instance.save()
        changed = self.instance.name_changed
        self.instance.save()
        self.assertEquals(self.instance.name_changed, changed)

        
class ChoicesTests(TestCase):
    def setUp(self):
        self.STATUS = Choices('DRAFT', 'PUBLISHED')

    def test_getattr(self):
        self.assertEquals(self.STATUS.DRAFT, 'DRAFT')

    def test_indexing(self):
        self.assertEquals(self.STATUS[1], ('PUBLISHED', 'PUBLISHED'))

    def test_iteration(self):
        self.assertEquals(tuple(self.STATUS), (('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED')))

    def test_repr(self):
        self.assertEquals(repr(self.STATUS),
                          "Choices("
                          "('DRAFT', 'DRAFT', 'DRAFT'), "
                          "('PUBLISHED', 'PUBLISHED', 'PUBLISHED'))")

        
class LabelChoicesTests(ChoicesTests):
    def setUp(self):
        self.STATUS = Choices(
            ('DRAFT', 'is draft'),
            ('PUBLISHED', 'is published'),
            'DELETED',
        )

    def test_iteration(self):
        self.assertEquals(tuple(self.STATUS), (
            ('DRAFT', 'is draft'),
            ('PUBLISHED', 'is published'),
            ('DELETED', 'DELETED'))
        )

    def test_indexing(self):
        self.assertEquals(self.STATUS[1], ('PUBLISHED', 'is published'))

    def test_default(self):
        self.assertEquals(self.STATUS.DELETED, 'DELETED')

    def test_provided(self):
        self.assertEquals(self.STATUS.DRAFT, 'DRAFT')

    def test_repr(self):
        self.assertEquals(repr(self.STATUS),
                          "Choices("
                          "('DRAFT', 'DRAFT', 'is draft'), "
                          "('PUBLISHED', 'PUBLISHED', 'is published'), "
                          "('DELETED', 'DELETED', 'DELETED'))")

        
class IdentifierChoicesTests(ChoicesTests):
    def setUp(self):
        self.STATUS = Choices(
            (0, 'DRAFT', 'is draft'),
            (1, 'PUBLISHED', 'is published'),
            (2, 'DELETED', 'is deleted'))

    def test_iteration(self):
        self.assertEqual(tuple(self.STATUS), (
                (0, 'is draft'),
                (1, 'is published'),
                (2, 'is deleted')))

    def test_indexing(self):
        self.assertEquals(self.STATUS[1], (1, 'is published'))

    def test_getattr(self):
        self.assertEquals(self.STATUS.DRAFT, 0)
        
    def test_repr(self):
        self.assertEquals(repr(self.STATUS),
                          "Choices("
                          "(0, 'DRAFT', 'is draft'), "
                          "(1, 'PUBLISHED', 'is published'), "
                          "(2, 'DELETED', 'is deleted'))")

        
class InheritanceCastModelTests(TestCase):
    def setUp(self):
        self.parent = InheritParent.objects.create()
        self.child = InheritChild.objects.create()
    
    def test_parent_real_type(self):
        self.assertEquals(self.parent.real_type,
                          ContentType.objects.get_for_model(InheritParent))

    def test_child_real_type(self):
        self.assertEquals(self.child.real_type,
                          ContentType.objects.get_for_model(InheritChild))

    def test_cast(self):
        obj = InheritParent.objects.get(pk=self.child.pk).cast()
        self.assertEquals(obj.__class__, InheritChild)


class TimeStampedModelTests(TestCase):
    def test_created(self):
        t1 = TimeStamp.objects.create()
        t2 = TimeStamp.objects.create()
        self.assert_(t2.created > t1.created)

    def test_modified(self):
        t1 = TimeStamp.objects.create()
        t2 = TimeStamp.objects.create()
        t1.save()
        self.assert_(t2.modified < t1.modified)


class TimeFramedModelTests(TestCase):

    def setUp(self):
        self.now = datetime.now()
    
    def test_not_yet_begun(self):
        TimeFrame.objects.create(start=self.now+timedelta(days=2))
        self.assertEquals(TimeFrame.timeframed.count(), 0)

    def test_finished(self):
        TimeFrame.objects.create(end=self.now-timedelta(days=1))
        self.assertEquals(TimeFrame.timeframed.count(), 0)

    def test_no_end(self):
        TimeFrame.objects.create(start=self.now-timedelta(days=10))
        self.assertEquals(TimeFrame.timeframed.count(), 1)

    def test_no_start(self):
        TimeFrame.objects.create(end=self.now+timedelta(days=2))
        self.assertEquals(TimeFrame.timeframed.count(), 1)

    def test_within_range(self):
        TimeFrame.objects.create(start=self.now-timedelta(days=1),
                                 end=self.now+timedelta(days=1))
        self.assertEquals(TimeFrame.timeframed.count(), 1)

class TimeFrameManagerAddedTests(TestCase):

    def test_manager_available(self):
        self.assert_(isinstance(TimeFrameManagerAdded.timeframed, QueryManager))

class StatusModelTests(TestCase):
    def setUp(self):
        self.model = Status
        self.on_hold = Status.STATUS.on_hold
        self.active = Status.STATUS.active

    def test_created(self):
        c1 = self.model.objects.create()
        c2 = self.model.objects.create()
        self.assert_(c2.status_changed > c1.status_changed)
        self.assertEquals(self.model.active.count(), 2)
        self.assertEquals(self.model.deleted.count(), 0)

    def test_modification(self):
        t1 = self.model.objects.create()
        date_created = t1.status_changed
        t1.status = self.on_hold
        t1.save()
        self.assertEquals(self.model.active.count(), 0)
        self.assertEquals(self.model.on_hold.count(), 1)
        self.assert_(t1.status_changed > date_created)
        date_changed = t1.status_changed
        t1.save()
        self.assertEquals(t1.status_changed, date_changed)
        date_active_again = t1.status_changed
        t1.status = self.active
        t1.save()
        self.assert_(t1.status_changed > date_active_again)

        
class StatusModelPlainTupleTests(StatusModelTests):
    def setUp(self):
        self.model = StatusPlainTuple
        self.on_hold = StatusPlainTuple.STATUS[2][0]
        self.active = StatusPlainTuple.STATUS[0][0]

class StatusManagerAddedTests(TestCase):

    def test_manager_available(self):
        self.assert_(isinstance(StatusManagerAdded.active, QueryManager))

class QueryManagerTests(TestCase):
    def setUp(self):
        data = ((True, True, 0),
                (True, False, 4),
                (False, False, 2),
                (False, True, 3),
                (True, True, 1),
                (True, False, 5))
        for p, c, o in data:
            Post.objects.create(published=p, confirmed=c, order=o)

    def test_passing_kwargs(self):
        qs = Post.public.all()
        self.assertEquals([p.order for p in qs], [0, 1, 4, 5])

    def test_passing_Q(self):
        qs = Post.public_confirmed.all()
        self.assertEquals([p.order for p in qs], [0, 1])

    def test_ordering(self):
        qs = Post.public_reversed.all()
        self.assertEquals([p.order for p in qs], [5, 4, 1, 0])

if 'south' in settings.INSTALLED_APPS:
    class SouthFreezingTests(TestCase):
        def test_introspector_adds_no_excerpt_field(self):
            from south.modelsinspector import introspector
            mf = Article._meta.get_field('body')
            args, kwargs = introspector(mf)
            self.assertEquals(kwargs['no_excerpt_field'], 'True')
        
        def test_no_excerpt_field_works(self):
            from models import NoRendered
            self.assertRaises(FieldDoesNotExist,
                              NoRendered._meta.get_field,
                              '_body_excerpt')

class ManagerFromTests(TestCase):
    def setUp(self):
        Entry.objects.create(author='George', published=True)
        Entry.objects.create(author='George', published=False)
        Entry.objects.create(author='Paul', published=True)
    
    def test_chaining(self):
        self.assertEqual(Entry.objects.by_author('George').published().count(),
                         1)

    def test_function(self):
        self.assertEqual(Entry.objects.unpublished().count(), 1)