Skip to content

Commit

Permalink
Now the custom admin command accept even the typologies
Browse files Browse the repository at this point in the history
  • Loading branch information
Germano Guerrini committed Nov 2, 2015
1 parent e977611 commit 5a783ef
Show file tree
Hide file tree
Showing 3 changed files with 133 additions and 13 deletions.
18 changes: 16 additions & 2 deletions djangomaat/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ def _typology_getters_iterator(self):
for k, v in inspect.getmembers(self, predicate=inspect.ismethod)
if k.startswith(GETTER_PREFIX))

def _getters_iterator(self, typologies):
def getter_name(typology):
return '{}{}'.format(GETTER_PREFIX, typology)
return ((t, getattr(self, getter_name(t))) for t in typologies)

def _get_content_type(self):
"""
Caches and returns the content type of the model this handler is
Expand All @@ -126,19 +131,28 @@ def _get_content_type(self):
self._content_type = ct
return self._content_type

def flush_ordered_objects(self, logger=None, simulate=False):
def flush_ordered_objects(self, typologies=None, logger=None, simulate=False):
"""
Replaces all the current rankings for the model this handler is
attached to.
This method gets called by the management command.
"""
if typologies is not None:
if not isinstance(typologies, (list, tuple)):
typologies = [typologies]
for typology in typologies:
self._validate_typology(typology)
iterator = self._getters_iterator(typologies)
else:
iterator = self._typology_getters_iterator()

if logger is not None:
if simulate:
logger.write('Simulating flushing...\n')
else:
logger.write('Flushing...\n')

for typology, getter in self._typology_getters_iterator():
for typology, getter in iterator:

if logger is not None:
logger.write('Handler: {} - Typology: {}\n'.format(self, typology))
Expand Down
44 changes: 33 additions & 11 deletions djangomaat/management/commands/populate_maat_ranking.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import unicode_literals

from optparse import make_option
from string import strip

from django.core.management.base import BaseCommand
from django.db.models.loading import get_model
Expand All @@ -19,11 +20,25 @@ class Command(BaseCommand):
help='Simulation mode'),
)

def get_model_from_arg(self, arg):
app_label, model_name = arg.split('.')
return get_model(app_label, model_name)
def _parse(self, model):
"""
Parse a string like
app_label.model_name:typology1,typology2
into a tuple
(app_label, model_name, [typology1, typology2])
def handle(self, *args, **options):
Typologies are not mandatory unless a colon char is in the string.
"""
bits = model.split(':')
app_label, model_name = bits[0].split('.')
typologies = None
if len(bits) > 1:
typologies = map(strip, bits[1].split(','))
if not typologies:
raise SyntaxError('Missing typologyes values after colon')
return app_label, model_name, typologies

def handle(self, *models, **options):
simulate = options['simulate']
verbosity = options['verbosity']

Expand All @@ -32,14 +47,21 @@ def handle(self, *args, **options):
else:
logger = None

if args:
handlers = [maat.get_handler_for_model(self.get_model_from_arg(i))
for i in args]
if models:
for model in models:
app_label, model_name, typologies = self._parse(model)
model_obj = get_model(app_label, model_name)
handler = maat.get_handler_for_model(model_obj)
handler.flush_ordered_objects(
typologies=typologies,
logger=logger,
simulate=simulate
)
else:
handlers = maat.get_registered_handlers()

if not handlers and verbosity > 0:
self.stdout.write('No registered handlers found.\n')
if not handlers and verbosity > 0:
self.stdout.write('No registered handlers found.\n')

for handler in handlers:
handler.flush_ordered_objects(logger=logger, simulate=simulate)
for handler in handlers:
handler.flush_ordered_objects(logger=logger, simulate=simulate)
84 changes: 84 additions & 0 deletions djangomaat/tests.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import unittest

from django.core.management import call_command
from django.db import models
try:
from django.contrib.contenttypes.fields import ReverseGenericRelatedObjectsDescriptor
except ImportError:
# Django < 1.7
from django.contrib.contenttypes.generic import ReverseGenericRelatedObjectsDescriptor
from django.utils.six import StringIO

from djangomaat.register import maat
from djangomaat.handlers import MaatHandler
from djangomaat.exceptions import *


class TestMaatHandler(MaatHandler):

def get_pk_list_for_typology1(self):
Expand Down Expand Up @@ -176,3 +179,84 @@ def test_simulated_and_logged_flush_and_retrieve(self):
self.assertEqual(list(TestModel.maat.ordered_by('typology1')), [])
TestModel.objects.all().delete()
maat.unregister(TestModel)

def test_flush_and_retrieve_typology(self):
maat.register(TestModel, TestMaatHandler)
object1 = TestModel.objects.create(name='object1')
object2 = TestModel.objects.create(name='object2')
object3 = TestModel.objects.create(name='object3')
object4 = TestModel.objects.create(name='object4')
object5 = TestModel.objects.create(name='object5')
self.h.flush_ordered_objects('typology1')
expected = [object1, object2, object3, object4, object5]
self.assertEqual(list(TestModel.maat.ordered_by('typology1')), expected)
expected.reverse()
self.assertEqual(list(TestModel.maat.ordered_by('-typology1')), expected)
TestModel.objects.all().delete()
maat.unregister(TestModel)

def test_flush_and_retrieve_typology_list(self):
maat.register(TestModel, TestMaatHandler)
object1 = TestModel.objects.create(name='object1')
object2 = TestModel.objects.create(name='object2')
object3 = TestModel.objects.create(name='object3')
object4 = TestModel.objects.create(name='object4')
object5 = TestModel.objects.create(name='object5')
self.h.flush_ordered_objects(['typology1', 'typology2'])
expected = [object1, object2, object3, object4, object5]
self.assertEqual(list(TestModel.maat.ordered_by('typology1')), expected)
expected.reverse()
self.assertEqual(list(TestModel.maat.ordered_by('-typology1')), expected)
self.assertEqual(list(TestModel.maat.ordered_by('typology2')), [])
self.assertEqual(list(TestModel.maat.ordered_by('-typology2')), [])
TestModel.objects.all().delete()
maat.unregister(TestModel)

def test_flush_and_retrieve_typology_wrong(self):
maat.register(TestModel, TestMaatHandler)
self.assertRaises(
TypologyNotImplemented,
self.h.flush_ordered_objects,
'typology3'
)
maat.unregister(TestModel)

def test_command_output_no_handlers(self):
out = StringIO()
call_command('populate_maat_ranking', stdout=out, **{'verbosity': 1})
self.assertIn('No registered handlers found.', out.getvalue())

def test_command_output_automatic_handlers(self):
maat.register(TestModel, TestMaatHandler)
out = StringIO()
call_command('populate_maat_ranking', stdout=out, **{'verbosity': 1})
self.assertIn('Handler: djangomaat.testmodel - Typology: typology1', out.getvalue())
self.assertIn('Handler: djangomaat.testmodel - Typology: typology2', out.getvalue())
maat.unregister(TestModel)

def test_command_output_given_handlers(self):
maat.register(TestModel, TestMaatHandler)
out = StringIO()
args = ['djangomaat.testmodel']
call_command('populate_maat_ranking', stdout=out, *args, **{'verbosity': 1})
self.assertIn('Handler: djangomaat.testmodel - Typology: typology1', out.getvalue())
self.assertIn('Handler: djangomaat.testmodel - Typology: typology2', out.getvalue())
maat.unregister(TestModel)

def test_command_output_given_handlers_and_typology(self):
maat.register(TestModel, TestMaatHandler)
out = StringIO()
args = ['djangomaat.testmodel:typology1']
call_command('populate_maat_ranking', stdout=out, *args, **{'verbosity': 1})
self.assertIn('Handler: djangomaat.testmodel - Typology: typology1', out.getvalue())
self.assertNotIn('typology2', out.getvalue())
maat.unregister(TestModel)

def test_command_output_given_all_handlers_ad_typologies(self):
maat.register(TestModel, TestMaatHandler)
out = StringIO()
args = ['djangomaat.testmodel:typology1,typology2']
call_command('populate_maat_ranking', stdout=out, *args, **{'verbosity': 1})
self.assertIn('Handler: djangomaat.testmodel - Typology: typology1', out.getvalue())
self.assertIn('Handler: djangomaat.testmodel - Typology: typology2', out.getvalue())
maat.unregister(TestModel)

0 comments on commit 5a783ef

Please sign in to comment.