Commits

Omer Katz committed 933be08

Completed TreeFactory, DateFormattedTreeItemFactory, YearTreeItemFactory
and MonthTreeItemFactory with tests.

Comments (0)

Files changed (8)

autotree/factories.py

+from django.core import urlresolvers
+from sitetree.models import Tree, TreeItem
+
+class TreeFactory(object):
+    def __init__(self, alias):
+        self.alias = alias
+
+    def get_or_create(self):
+        Tree.objects.get_or_create(alias=self.alias)
+
+class DateFormattedTreeItemFactory(object):
+    def __init__(self,
+                 view_name,
+                 tree_alias,
+                 is_in_menu=True,
+                 is_in_breadcrumbs=True,
+                 is_in_sitetree=True,
+                 logged_in_only_access=False,
+                 restricted_only_access=False,
+                 access_permissions = [],
+                 access_perm_type = 1):
+        self.view_name = view_name
+        self.tree_factory = TreeFactory(tree_alias)
+        self.is_in_menu = is_in_menu
+        self.is_in_breadcrumbs = is_in_breadcrumbs
+        self.is_in_sitetree = is_in_sitetree
+        self.logged_in_only_access = logged_in_only_access
+        self.restricted_only_access = restricted_only_access
+        self.access_permissions = access_permissions
+        self.access_perm_type = access_perm_type
+
+    def get_formatted_date(self, date):
+        raise NotImplementedError('This function must be implemented in a derived class')
+
+    def get_parent(self, date):
+        raise NotImplementedError('This function must be implemented in a derived class')
+    
+    def get_url(self, formatted_date):
+        return urlresolvers.reverse(self.view_name, args=[formatted_date])
+
+    def get_or_create(self, date):
+        title = self.get_formatted_date(date)
+        url = self.get_url(title)
+        tree = self.tree_factory.get_or_create()
+        parent = self.get_parent(date)
+
+        TreeItem.objects.get_or_create(title=title, url=url, tree=tree, parent=parent)
+
+class YearTreeItemFactory(DateFormattedTreeItemFactory):
+    def __init__(self,
+                 view_name,
+                 tree_alias,
+                 is_in_menu=True,
+                 is_in_breadcrumbs=True,
+                 is_in_sitetree=True,
+                 logged_in_only_access=False,
+                 restricted_only_access=False,
+                 access_permissions = [],
+                 access_perm_type = 1):
+        super(YearTreeItemFactory, self).__init__(view_name,
+                                                  tree_alias,
+                                                  is_in_menu,
+                                                  is_in_breadcrumbs,
+                                                  is_in_sitetree,
+                                                  logged_in_only_access,
+                                                  restricted_only_access,
+                                                  access_permissions,
+                                                  access_perm_type)
+
+    def get_formatted_date(self, date):
+        return date.strftime('%Y')
+
+    def get_parent(self, date):
+        return None
+
+class MonthTreeItemFactory(DateFormattedTreeItemFactory):
+    def __init__(self,
+                 view_name,
+                 tree_alias,
+                 is_in_menu=True,
+                 is_in_breadcrumbs=True,
+                 is_in_sitetree=True,
+                 logged_in_only_access=False,
+                 restricted_only_access=False,
+                 access_permissions = [],
+                 access_perm_type = 1):
+        super(MonthTreeItemFactory, self).__init__(view_name,
+                                                  tree_alias,
+                                                  is_in_menu,
+                                                  is_in_breadcrumbs,
+                                                  is_in_sitetree,
+                                                  logged_in_only_access,
+                                                  restricted_only_access,
+                                                  access_permissions,
+                                                  access_perm_type)
+
+        self.year_tree_item_factory = YearTreeItemFactory(view_name,
+                                                          tree_alias,
+                                                          is_in_menu,
+                                                          is_in_breadcrumbs,
+                                                          is_in_sitetree,
+                                                          logged_in_only_access,
+                                                          restricted_only_access,
+                                                          access_permissions,
+                                                          access_perm_type)
+
+    def get_formatted_date(self, date):
+        return date.strftime('%B')
+
+    def get_parent(self, date):
+        return self.year_tree_item_factory.get_or_create(date)
+
+class AutoTreeItemFactory(object):
+    def __init__(self,
+                 tree_alias,
+                 is_in_menu=True,
+                 is_in_breadcrumbs=True,
+                 is_in_sitetree=True,
+                 is_url_a_pattern=False,
+                 logged_in_only_access=False,
+                 restricted_only_access=False,
+                 access_permissions = [],
+                 access_perm_type = 1,
+                 **kwargs):
+        self.tree_alias = tree_alias
+        self.is_in_menu = is_in_menu
+        self.is_in_breadcrumbs = is_in_breadcrumbs
+        self.is_in_sitetree = is_in_sitetree
+        self.is_url_a_pattern = is_url_a_pattern
+        self.logged_in_only_access = logged_in_only_access
+        self.restricted_only_access = restricted_only_access
+        self.access_permissions = access_permissions
+        self.access_perm_type = access_perm_type
+
+    def resolve_title(self, model_instance):
+        pass
+
+    def resolve_parent(self, model_instance):
+        pass
+
+    def resolve_url(self, model_instance):
+        pass
+
+    def resolve_hint(self, model_instance):
+        pass
+
+    def resolve_description(self, model_instance):
+        pass
+
+    def resolve_sort_order(self, model_instance):
+        pass
+
+    def create_tree(self):
+        pass
+
+    def create_item(self, model_instance, **kwargs):
+        pass
+
+    def create(self, model_instance, **kwargs):
+        pass
+  

autotree/fields.py

+from django.db import models
+from django.db.models.fields.subclassing import SubfieldBase
+from sitetree.models import TreeItem
 
-  
+try:
+    from south.modelsinspector import introspector
+except ImportError:
+    pass
+
+class AutoArchiveTreeItemField(models.ForeignKey):
+    #__metaclass__ = SubfieldBase
+
+    def __init__(self, *args, **kwargs):
+        options = {'null': True}
+        options.update(kwargs)
+        super(AutoArchiveTreeItemField, self).__init__(TreeItem, **options)
+
+    def contribute_to_class(self, cls, name):
+
+        super(AutoArchiveTreeItemField, self).contribute_to_class(cls, name)
+        setattr(cls, self.name, self)
+
+    def contribute_to_related_class(self, cls, related):
+        #print cls
+        #print self
+        #print related
+
+        pass

autotree/models.py

 from django.db import models
+from autotree.fields import AutoArchiveTreeItemField
 
-# Create your models here.
+class Test(models.Model):
+    test = AutoArchiveTreeItemField()

autotree/tests.py

-"""
-This file demonstrates writing tests using the unittest module. These will pass
-when you run "manage.py test".
+import datetime
+from time import strftime
+from django.core import urlresolvers
+from django.db.models.manager import Manager
+from django.test import TestCase
+from mock import Mock
+from sitetree.models import  TreeItem, Tree
+from autotree.factories import DateFormattedTreeItemFactory, TreeFactory, YearTreeItemFactory, MonthTreeItemFactory
 
-Replace this with more appropriate tests for your application.
-"""
+class TreeFactoryTests(TestCase):
+    def setUp(self):
+        self.factory = TreeFactory('test')
+        Tree.objects = self.mock_tree_manager()
 
-from django.test import TestCase
+    def tearDown(self):
+        Tree.objects = Manager()
 
+    def test_that_when_requesting_the_tree_the_tree_manager_get_or_create_method_is_called_with_the_right_alias(self):
+        self.factory.get_or_create()
+        Tree.objects.get_or_create.assert_called_once_with(alias = 'test')
 
-class SimpleTest(TestCase):
-    def test_basic_addition(self):
-        """
-        Tests that 1 + 1 always equals 2.
-        """
-        self.assertEqual(1 + 1, 2)
+    def mock_tree_manager(self):
+        mock = Mock(spec_set=Manager)
+
+        return mock
+
+class DateFormattedTreeItemFactoryTests(TestCase):
+    def setUp(self):
+        TreeItem.objects = self.mock_tree_item_manager()
+        self.factory = DateFormattedTreeItemFactory('test', 'test')
+
+        self.reverse_func = urlresolvers.reverse
+
+        urlresolvers.reverse = Mock()
+        urlresolvers.reverse.return_value = '/test/'
+
+    def tearDown(self):
+        TreeItem.objects = Manager()
+
+        urlresolvers.reverse = self.reverse_func
+
+    def test_that_when_requesting_the_tree_item_the_tree_factory_get_or_create_is_called(self):
+        self.mock_tree_factory()
+        self.mock_get_formatted_date()
+        self.mock_get_parent()
+
+        self.factory.get_or_create(datetime.datetime.now())
+
+        self.factory.tree_factory.get_or_create.assert_called_once_with()
+
+    def test_that_when_requesting_the_tree_item_url_the_url_is_reversed_by_the_provided_view_name(self):
+        self.factory.get_url(datetime.datetime.now().strftime('%Y'))
+
+        urlresolvers.reverse.assert_called_once_with('test', args=[datetime.datetime.now().strftime('%Y')])
+
+    def test_that_when_requesting_the_tree_item_the_arguments_are_correct(self):
+        self.mock_tree_factory()
+        self.mock_get_formatted_date()
+        self.mock_get_parent()
+
+        self.factory.get_or_create(datetime.datetime.now())
+
+        TreeItem.objects.get_or_create.assert_called_once_with(title='test', url='/test/', tree=Tree(alias='test'), parent=TreeItem(title='parent'))
+
+    def mock_tree_item_manager(self):
+        mock = Mock(spec_set=Manager)
+
+        return mock
+
+    def mock_tree_factory(self):
+        self.factory.tree_factory = Mock(spec_set=TreeFactory)
+        self.factory.tree_factory.get_or_create.return_value = Tree(alias='test')
+
+    def mock_get_formatted_date(self):
+        self.factory.get_formatted_date = Mock()
+        self.factory.get_formatted_date.return_value = 'test'
+
+    def mock_get_parent(self):
+        self.factory.get_parent = Mock()
+        self.factory.get_parent.return_value = TreeItem(title='parent')
+
+class YearTreeItemFactoryTests(TestCase):
+    def setUp(self):
+        TreeItem.objects = self.mock_tree_item_manager()
+        self.factory = YearTreeItemFactory('test', 'test')
+
+        self.reverse_func = urlresolvers.reverse
+
+        urlresolvers.reverse = Mock()
+        urlresolvers.reverse.return_value = '/test/'
+
+    def tearDown(self):
+        TreeItem.objects = Manager()
+
+        urlresolvers.reverse = self.reverse_func
+
+    def mock_tree_item_manager(self):
+        mock = Mock(spec_set=Manager)
+
+        return mock
+
+    def test_that_when_requesting_the_tree_item_formatted_date_the_return_value_is_the_year(self):
+        self.assertEqual(self.factory.get_formatted_date(datetime.datetime.now()), datetime.datetime.now().strftime('%Y'))
+
+    def test_that_when_requesting_the_tree_item_parent_the_return_value_is_none(self):
+        self.assertEqual(self.factory.get_parent(datetime.datetime.now()), None)
+
+    def test_that_when_requesting_the_tree_item_the_arguments_are_correct(self):
+        self.mock_tree_factory()
+
+        self.factory.get_or_create(datetime.datetime.now())
+        year = datetime.datetime.now().strftime('%Y')
+        TreeItem.objects.get_or_create.assert_called_once_with(title=year, url='/test/', tree=Tree(alias='test'), parent=None)
+
+    def mock_tree_factory(self):
+        self.factory.tree_factory = Mock(spec_set=TreeFactory)
+        self.factory.tree_factory.get_or_create.return_value = Tree(alias='test')
+
+class MonthItemFactoryTests(TestCase):
+    def setUp(self):
+        TreeItem.objects = self.mock_tree_item_manager()
+        self.factory = MonthTreeItemFactory('test', 'test')
+
+        self.reverse_func = urlresolvers.reverse
+
+        urlresolvers.reverse = Mock()
+        urlresolvers.reverse.return_value = '/test/'
+
+    def tearDown(self):
+        TreeItem.objects = Manager()
+
+        urlresolvers.reverse = self.reverse_func
+
+    def mock_tree_item_manager(self):
+        mock = Mock(spec_set=Manager)
+
+        return mock
+
+    def test_that_when_requesting_the_tree_item_formatted_date_the_return_value_is_the_month_name(self):
+        self.assertEqual(self.factory.get_formatted_date(datetime.datetime.now()), datetime.datetime.now().strftime('%B'))
+
+    def test_that_when_requesting_the_tree_item_parent_the_the_year_tree_item_is_requested(self):
+        self.mock_year_tree_item_factory()
+
+        self.factory.get_parent(datetime.datetime.now())
+
+        self.factory.year_tree_item_factory.get_or_create.assert_called_once_with(datetime.datetime.now())
+
+    def test_that_when_requesting_the_tree_item_the_arguments_are_correct(self):
+        self.mock_tree_factory()
+
+        self.factory.get_or_create(datetime.datetime.now())
+        year = datetime.datetime.now().strftime('%B')
+        TreeItem.objects.get_or_create.assert_called_with(title=year, url='/test/', tree=Tree(alias='test'), parent=None)
+
+    def mock_tree_factory(self):
+        self.factory.tree_factory = Mock(spec_set=TreeFactory)
+        self.factory.tree_factory.get_or_create.return_value = Tree(alias='test')
+
+    def mock_year_tree_item_factory(self):
+        self.factory.year_tree_item_factory = Mock()

autotree/utils.py

+def invoke_or_return(value, **kwargs):
+    return value(**kwargs) if callable(value) else value
+
+def mixin_instance(instance, *args):
+
+    for mixin in args:
+        if mixin in instance.__class__.__bases__:
+            raise TypeError()
+            
+        instance.__class__.__bases__ += (mixin, )
+
+    return instance
+from fabric.decorators import task
+from fabric.api import run
+
+@task
+def publish():
+    run('python setup.py register sdist bdist_egg upload')
+
+@task
+def run_tests():
+    from django.conf import settings
+
+    settings.configure(INSTALLED_APPS=['autotree'],
+                       DATABASES = {
+                                        'default': {
+                                            'ENGINE': 'django.db.backends.sqlite3',
+                                            'NAME': '.'
+                                        }
+                                    })
+
+    from django.test.utils import setup_test_environment
+
+    setup_test_environment()
+
+    from django.test.simple import run_tests
+
+    run_tests(['autotree'])
+  
+import sys
+
+def run_app_tests():
+    from django.conf import settings
+
+    settings.configure(INSTALLED_APPS=['autotree', 'sitetree'],
+                       DATABASES = {
+                                        'default': {
+                                            'ENGINE': 'django.db.backends.sqlite3',
+                                            'NAME': '.'
+                                        }
+                                    })
+
+    from django.test.utils import setup_test_environment
+
+    setup_test_environment()
+
+    from django.test.simple import run_tests
+
+    if run_tests(['autotree']):
+        sys.exit(1)
+
+run_app_tests()
 readme = f.read()
 f.close()
 
-def run_tests():
+def run_app_tests():
     from django.conf import settings
 
     settings.configure(INSTALLED_APPS=['autotree'],
 
     return status_classifiers[status]
 
-run_tests()
+run_app_tests()
 
 setup(
     name='django-autotree',
     url='http://bitbucket.org/the_drow/django-autotree',
     packages=['autotree'],
     include_package_data=True,
-    install_requires=['setuptools', 'django', 'django-sitetree>=0.3'],
+    install_requires=['setuptools>=0.6c11', 'django>=1.2', 'django-sitetree>=0.3'],
     zip_safe=False,
     classifiers=[
         get_development_status(__status__),