Conjunto de mudanças 6498 no repositório publico


Ignorar:
Timestamp:
14/06/2012 21:02:41 (9 anos atrás)
Autor:
mazza
Mensagem:

refatoracao: eliminado BoxManager?, metodos integrados a Box

Localização:
PortalInterlegis/produtos/il.portalinterlegis/trunk/src/il/portalinterlegis
Arquivos:
1 removido
4 editados

Legenda:

Não Modificado
Adicionado
Removido
  • PortalInterlegis/produtos/il.portalinterlegis/trunk/src/il/portalinterlegis/browser/boxes/manager.py

    r6497 r6498  
     1from exceptions import ValueError
     2
    13import martian
    24from AccessControl import getSecurityManager
     
    2325provideAdapter(PersistentDictionaryField)
    2426
    25 templates = Environment(loader=PackageLoader(__name__))
     27template_factory = Environment(loader=PackageLoader(__name__))
    2628
    27 class BoxManager(object):
     29class Box(object):
    2830
    2931    ALL_BOXES_KEY = 'il.portalinterlegis.boxes'
    3032
    31     def __init__(self, schema, label=None):
     33    BOX_TEMPLATE = '''
     34      <div id="%s"%s>
     35%s
     36      </div>'''
     37
     38    def __init__(self, schema, number, permission=ModifyPortalContent, form_label=None):
    3239        self.schema = schema
     40        self.number = number
     41        self.permission = permission
    3342        #TODO: improve this text
    34         self.form_label = label or u'Edite os valore desta caixa'
     43        self.form_label = form_label or u'Edite os valore desta caixa'
    3544
    36     def build_form(self, number):
     45    def __call__(self, context):
     46        is_editable = getSecurityManager().checkPermission(self.permission, context)
     47        return self.BOX_TEMPLATE % (self.key,
     48                                    ' class ="editable-box"' if is_editable else '',
     49                                    self.template.render(self.content(context)))
    3750
    38         # the combination (form.EditForm, grok.View)
    39         # is from https://mail.zope.org/pipermail/grok-dev/2008-July/005999.html
    40         # (plone.directives.form.EditForm did not work well)
    41         class BoxEditForm(AutoExtensibleForm, form.EditForm, grok.View):
    42             grok.context(IFolderish)
    43             grok.name(self._box_name_for_url(number))
    44             grok.require('cmf.ModifyPortalContent')
     51    def content(self, context):
     52        annotations = IAnnotations(context)
     53        boxes = get_or_create_persistent_dict(annotations, self.ALL_BOXES_KEY)
     54        return get_or_create_persistent_dict(boxes, self.key)
    4555
    46             label = self.form_label
    47             schema = self.schema
     56    @property
     57    def template(self):
     58        return template_factory.get_template(
     59            self.schema.__name__.lower() + '.html')
    4860
    49             def getContent(form_self):
    50                 return self.box_content(form_self.context, number)
     61    @property
     62    def key(self):
     63        return '%s_%s' % (self.schema.__name__, self.number)
    5164
    52             def render(self):
    53                 # we cannot simply associtate this template in the class level
    54                 # because form.EditForm has a ".render()" method and grok.View
    55                 # assumes you cannot have both "template = ..." and ".render()".
    56                 # No problem, we make a method that simply renders the template
    57                 template = ZopeTwoPageTemplate(filename="boxform.pt")
    58                 return template.render(self)
     65    @property
     66    def form_name(self):
     67        """Last part of form urls.
     68        """
     69        return 'box_%s' % self.key
    5970
    60         globals()['BoxEditForm_%s' % self._box_key(number)] = BoxEditForm
    61         return BoxEditForm
     71def build_box_form(box):
    6272
    63     def build_n_forms(self, max_number):
    64         for number in range(1, max_number+1):
    65             self.build_form(number)
     73    # the combination (form.EditForm, grok.View)
     74    # is from https://mail.zope.org/pipermail/grok-dev/2008-July/005999.html
     75    # (plone.directives.form.EditForm did not work well)
     76    class BoxEditForm(AutoExtensibleForm, form.EditForm, grok.View):
     77        grok.context(IFolderish)
     78        grok.name(box.form_name)
     79        grok.require('cmf.ModifyPortalContent')
    6680
    67     def box_content(self, context, number): # maybe this method should be private
    68         annotations = IAnnotations(context)
    69         boxes = get_or_create_persistent_dict(annotations, BoxManager.ALL_BOXES_KEY)
    70         return get_or_create_persistent_dict(boxes, self._box_key(number))
     81        label = box.form_label
     82        schema = box.schema
    7183
    72     def html(self, context, number):
    73         template = templates.get_template(self.schema.__name__.lower() + '.html')
    74         return template.render(self.box_content(context, number))
     84        def getContent(self):
     85            return box.content(self.context)
    7586
    76     def _box_key(self, number):
    77         return '%s_%s' % (self.schema.__name__, number)
     87        def render(self):
     88            # we cannot simply associtate this template in the class level
     89            # because form.EditForm has a ".render()" method and grok.View
     90            # assumes you cannot have both "template = ..." and ".render()".
     91            # No problem, we make a method that simply renders the template
     92            template = ZopeTwoPageTemplate(filename="boxform.pt")
     93            return template.render(self)
    7894
    79     def _box_name_for_url(self, number):
    80         return 'box_%s' % self._box_key(number)
     95    globals()['BoxEditForm_%s' % box.key] = BoxEditForm
     96    return BoxEditForm
    8197
     98def build_many_box_forms(schema, max_number):
     99    for number in range(1, max_number+1):
     100        build_box_form(Box(schema, number))
    82101
    83102def get_or_create_persistent_dict(dictionary, key):
     
    86105        dictionary[key] = value = PersistentDict()
    87106    return value
    88 from exceptions import ValueError
     107
    89108# ROWS
    90109class DtRow(object):
     
    123142
    124143
    125 class Box(object):
    126 
    127     BOX_TEMPLATE = '''
    128       <div id="%s"%s>%s
    129       </div>'''
    130 
    131     def __init__(self, schema, number, permission=ModifyPortalContent):
    132         self.schema = schema
    133         self.number = number
    134         self.permission = permission
    135 
    136     def __call__(self, context):
    137         boxmanager = BoxManager(self.schema)
    138         is_editable = getSecurityManager().checkPermission(self.permission, context)
    139         return self.BOX_TEMPLATE % (boxmanager._box_key(self.number),
    140                                     ' class ="editable-box"' if is_editable else '',
    141                                     boxmanager.html(context, self.number))
    142 
    143 
    144144class GridView(grok.View):
    145145    "Base class for all grid-like views"
     
    156156
    157157# initialize all the box managers
     158for s in box_schemas():
     159    build_many_box_forms(s, 10)
    158160
    159 for s in box_schemas():
    160     BoxManager(s).build_n_forms(10)
    161 
  • PortalInterlegis/produtos/il.portalinterlegis/trunk/src/il/portalinterlegis/browser/boxes/templates/isimplebox.html

    r6495 r6498  
    1       <div class="simple-box">
    2         <a href="/portal/{{target}}">
    3           <h2>{{title}}</h2>
    4           <h3 class="icon-news">{{subtitle}}</h3>
    5           <p>
    6             {{text}}
    7           </p>
    8         </a>
    9       </div>
     1        <div class="simple-box">
     2          <a href="/portal/{{target}}">
     3            <h2>{{title}}</h2>
     4            <h3 class="icon-news">{{subtitle}}</h3>
     5            <p>
     6              {{text}}
     7            </p>
     8          </a>
     9        </div>
  • PortalInterlegis/produtos/il.portalinterlegis/trunk/src/il/portalinterlegis/tests/testintegration.py

    r6495 r6498  
    77from fixtures import IL_PORTALINTERLEGIS_INTEGRATION_TESTING
    88from il.portalinterlegis.browser.boxes.interfaces import ISimpleBox
    9 from il.portalinterlegis.browser.boxes.manager import BoxManager
     9from il.portalinterlegis.browser.boxes.manager import Box, build_box_form
    1010from il.portalinterlegis.browser.interfaces import \
    1111     IComunidadeLegislativa, IInformacao, ICapacitacao, ITecnologia, IComunicacao
     
    7373
    7474    def test_box_content_is_empty_before_visiting_form(self):
    75         self.assertEqual({}, BoxManager(ISimpleBox).box_content(self.portal, 1))
     75        self.assertEqual({}, Box(ISimpleBox, 1).content(self.portal))
    7676
    7777    def test_using_box_form_creates_box_content(self):
    7878        context = self.portal
    79         boxmanager = BoxManager(ISimpleBox)
    8079
    81         def use_box_form(title, subtitle, text, target, num):
     80        def use_box_form(title, subtitle, text, target, box):
    8281            browser = self.layer.manager_browser()
    83             browser.open(self.url(boxmanager._box_name_for_url(num)))
     82            browser.open(self.url(box.form_name))
    8483            browser.getControl(name='form.widgets.title').value = title
    8584            browser.getControl(name='form.widgets.subtitle').value = subtitle
     
    8988            browser.getControl(name='form.buttons.apply').click()
    9089
    91         use_box_form('TIT_1', 'SUBTIT_1', 'TEXT_1', 'ALVO_1', 1)
    92         use_box_form('TIT_2', 'SUBTIT_2', 'TEXT_2', 'ALVO_2', 2)
     90        box_1 = Box(ISimpleBox, 1)
     91        use_box_form('TIT_1', 'SUBTIT_1', 'TEXT_1', 'ALVO_1', box_1)
    9392        self.assertEqual({'title': 'TIT_1', 'subtitle': 'SUBTIT_1', 'text': 'TEXT_1', 'target': None},
    94                          boxmanager.box_content(context, 1))
     93                         box_1.content(context))
     94
     95        # a second one to test there is no mutual interference
     96        box_2 = Box(ISimpleBox, 2)
     97        use_box_form('TIT_2', 'SUBTIT_2', 'TEXT_2', 'ALVO_2', box_2)
    9598        self.assertEqual({'title': 'TIT_2', 'subtitle': 'SUBTIT_2', 'text': 'TEXT_2', 'target': None},
    96                          boxmanager.box_content(context, 2))
     99                         box_2.content(context))
    97100
    98101    def test_box_forms_numbers_begin_from_1_not_zero(self):
    99102        with self.assertRaises(NotFound):
    100103            browser = self.layer.manager_browser()
    101             browser.open(self.url(BoxManager(ISimpleBox)._box_name_for_url(0)))
     104            browser.open(self.url(Box(ISimpleBox, 0).form_name))
    102105
    103106    def test_box_forms_are_limited(self):
    104107        with self.assertRaises(NotFound):
    105108            browser = self.layer.manager_browser()
    106             browser.open(self.url(BoxManager(ISimpleBox)._box_name_for_url(1000000)))
     109            browser.open(self.url(Box(ISimpleBox, 1000000).form_name))
    107110
    108111    def test_box_form_cannot_be_created_after_initialization(self):
    109         BoxManager(ISimpleBox).build_form(99) # try to build a box form in an arbitrary moment
     112        """Try to build a box form in an arbitrary moment.
     113           Unfortunately that's not possible.
     114        """
     115        build_box_form(Box(ISimpleBox, 99))
    110116        with self.assertRaises(NotFound):
    111117            browser = self.layer.manager_browser()
    112             browser.open(self.url(BoxManager(ISimpleBox)._box_name_for_url(99)))
     118            browser.open(self.url(Box(ISimpleBox, 99).form_name))
  • PortalInterlegis/produtos/il.portalinterlegis/trunk/src/il/portalinterlegis/tests/testunitboxes.py

    r6497 r6498  
    33from mock import patch
    44
    5 from il.portalinterlegis.browser.boxes.manager import BoxManager, DtRow
    6 from il.portalinterlegis.browser.boxes.interfaces import ISimpleBox
    7 from mockutils import *
     5from il.portalinterlegis.browser.boxes.manager import Box, DtRow
    86from itertools import count
     7from mock import MagicMock as Mock
    98
    10 _any_ = None # anything, doesn't really matter
     9diff_count = count(1)
    1110
    1211class TestUnitBoxes(unittest.TestCase):
     
    1514
    1615    def setUp(self):
    17         self.diff_count = count(1)
     16        pass
    1817
    1918    def assertMultiLineEqual(self, first, second, *args):
     
    2726        second = second.strip()
    2827        if first != second:
    29             c = self.diff_count.next()
     28            c = diff_count.next()
    3029            for i, s in enumerate([first, second]):
    3130                with open("out_%s.%s" % (c, i), "w+") as f:
     
    3332        super(TestUnitBoxes, self).assertMultiLineEqual(first, second, *args)
    3433
    35     def test_html(self):
    36         with patch.object(BoxManager, 'box_content') as mock:
    37             mock.return_value = {'title': 'TIT_1', 'subtitle': 'SUBTIT_1', 'text': 'TEXT_1', 'target': 'alvo'}
     34    def test_box_render_basic(self):
    3835
    39             boxmanager = BoxManager(ISimpleBox)
     36        with patch('il.portalinterlegis.browser.boxes.manager.template_factory',
     37                   template_factory_stub('        XXXX')):
     38
     39            box = Box(IStubBox, 1)
     40            box.content = Mock(
     41                return_value = {'var': 'XXXX'})
     42            context = object()
    4043            self.assertMultiLineEqual('''
    41       <div class="simple-box">
    42         <a href="/portal/alvo">
    43           <h2>TIT_1</h2>
    44           <h3 class="icon-news">SUBTIT_1</h3>
    45           <p>
    46             TEXT_1
    47           </p>
    48         </a>
    49       </div>
    50         ''', boxmanager.html(_any_, _any_))
     44      <div id="IStubBox_1">
     45        XXXX
     46      </div>''', box(context))
     47            box.content.assert_called_with(context)
    5148
    52     def test_row(self):
     49    def test_box_render_editable(self):
     50        with patch('il.portalinterlegis.browser.boxes.manager.template_factory',
     51                   template_factory_stub('        XXXX')):
     52            with patch('il.portalinterlegis.browser.boxes.manager.getSecurityManager') as security_mock:
     53                security_mock.checkPermission.return_value = True
     54
     55                box = Box(IStubBox, 1)
     56                box.content = Mock(
     57                    return_value = {'var': 'XXXX'})
     58                context = object()
     59                self.assertMultiLineEqual('''
     60      <div id="IStubBox_1" class ="editable-box">
     61        XXXX
     62      </div>''', box(context))
     63                box.content.assert_called_with(context)
     64
     65    def test_row_structure(self):
    5366        context = object()
    54         def mock_template(c):
    55             # A template is just a callable. A function will do.
    56             def f(context):
    57                 return "\n      %s" % (3*c)
    58             return f
    5967
    6068        self.assertMultiLineEqual('''
     
    7381    </div>
    7482  </div>
    75 ''', DtRow((1, mock_template('A')),
    76            (2, mock_template('B')),
    77            (3, mock_template('C')),
    78            (1, mock_template('D'))).render(context))
     83''', DtRow((1, Mock(return_value="\n      AAA")),
     84           (2, Mock(return_value="\n      BBB")),
     85           (3, Mock(return_value="\n      CCC")),
     86           (1, Mock(return_value="\n      DDD"))).render(context))
    7987
    8088
     89class IStubBox(object):
     90    pass
     91
     92class TemplateStub(object):
     93    def render(self, context):
     94        return "        %(var)s" % context
     95
     96def template_factory_stub(value):
     97    template_factory_stub = Mock()
     98    template_factory_stub.get_template.return_value = TemplateStub()
     99    return template_factory_stub
     100
Note: Veja TracChangeset para ajuda no uso do visualizador de conjunto de mudanças.
 

The contents and data of this website are published under license:
Creative Commons 4.0 Brasil - Atribuir Fonte - Compartilhar Igual.