testListBox.py 20.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2006 Nexedi SARL and Contributors. All Rights Reserved.
#          Yoshinori Okuji <yo@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

Jérome Perrin's avatar
Jérome Perrin committed
29 30

import unittest
31
from lxml import etree
32

33
import transaction
34 35 36 37 38
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from AccessControl.SecurityManagement import newSecurityManager
from zLOG import LOG
from Products.ERP5Type.tests.Sequence import SequenceList
from Testing import ZopeTestCase
39
from Products.ERP5Type.Globals import get_request
40
from Products.ERP5Type.tests.utils import createZODBPythonScript
41 42 43
from ZPublisher.HTTPRequest import FileUpload
from StringIO import StringIO
from Products.ERP5Form.Selection import Selection
44
from Products.ERP5Form.Form import ERP5Form
Nicolas Dumazet's avatar
Nicolas Dumazet committed
45
from Products.Formulator.TALESField import TALESMethod
46 47 48 49 50 51 52 53 54


class DummyFieldStorage:
  """A dummy FieldStorage to be wrapped in a FileUpload object.
  """
  def __init__(self):
    self.file = StringIO()
    self.filename = '<dummy field storage>'
    self.headers = {}
55 56 57 58 59 60

class TestListBox(ERP5TypeTestCase):
  """
    Test the API of ListBox. The user-visible aspect is tested
    by functional testing.
  """
61
  quiet = 1
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  run_all_test = 1

  def getBusinessTemplateList(self):
    # Use the same framework as the functional testing for convenience.
    # This adds some specific portal types and skins.
    return ('erp5_ui_test',)

  def getTitle(self):
    return "ListBox"

  def afterSetUp(self):
    self.login()

  def login(self):
    uf = self.getPortal().acl_users
    uf._doAddUser('seb', '', ['Manager'], [])
    user = uf.getUserById('seb').__of__(uf)
    newSecurityManager(None, user)

  def stepCreateObjects(self, sequence = None, sequence_list = None, **kw):
    # Make sure that the status is clean.
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

    message = portal.foo_module.FooModule_createObjects()
    self.failUnless('Created Successfully' in message)

  def stepModifyListBoxForStat(self, sequence = None, sequence_list = None, **kw):
    portal = self.getPortal()
    listbox = portal.FooModule_viewFooList.listbox
92 93 94
    message = listbox.ListBox_setPropertyList(
      field_stat_columns = 'id|FooModule_statId\ntitle|FooModule_statTitle',
      field_stat_method = 'portal_catalog')
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    self.failUnless('Set Successfully' in message)

  def stepRenderList(self, sequence = None, sequence_list = None, **kw):
    portal = self.getPortal()
    listbox = portal.FooModule_viewFooList.listbox
    request = get_request()
    request['here'] = portal.foo_module
    listboxline_list = listbox.get_value('default', render_format = 'list',
                                         REQUEST = request)
    sequence.edit(listboxline_list = listboxline_list)

  def stepCheckListBoxLineListWithStat(self, sequence = None, sequence_list = None, **kw):
    line_list = sequence.get('listboxline_list')
    self.assertEqual(len(line_list), 12)

    title_line = line_list[0]
    self.failUnless(title_line.isTitleLine())
    self.assertEqual(len(title_line.getColumnItemList()), 3)
    result = (('id', 'ID'), ('title', 'Title'), ('getQuantity', 'Quantity'))
    for i, (key, value) in enumerate(title_line.getColumnItemList()):
      self.assertEqual(key, result[i][0])
      self.assertEqual(value, result[i][1])

    for n, data_line in enumerate(line_list[1:-1]):
      self.failUnless(data_line.isDataLine())
      self.assertEqual(len(data_line.getColumnItemList()), 3)
      result = (('id', str(n)), ('title', 'Title %d' % n), ('getQuantity', str(10.0 - n)))
      for i, (key, value) in enumerate(data_line.getColumnItemList()):
        self.assertEqual(key, result[i][0])
        self.assertEqual(str(value).strip(), result[i][1])

    stat_line = line_list[-1]
    self.failUnless(stat_line.isStatLine())
    self.assertEqual(len(stat_line.getColumnItemList()), 3)
    result = (('id', 'foo_module'), ('title', 'Foos'), ('getQuantity', 'None'))
    for i, (key, value) in enumerate(stat_line.getColumnItemList()):
      self.assertEqual(key, result[i][0])
      self.assertEqual(str(value).strip(), result[i][1])

134
  def test_01_CheckListBoxLinesWithStat(self, quiet=quiet, run=run_all_test):
135 136 137 138 139 140 141 142 143 144 145 146 147 148
    if not run: return
    if not quiet:
      message = 'Test ListBoxLines With Statistics'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', 0, message)
    sequence_list = SequenceList()
    sequence_string = '\
                       CreateObjects \
                       Tic \
                       ModifyListBoxForStat \
                       RenderList \
                       CheckListBoxLineListWithStat \
                       '
    sequence_list.addSequenceString(sequence_string)
149 150
    sequence_list.play(self, quiet=quiet)

151
  def test_02_DefaultSort(self, quiet=quiet, run=run_all_test):
152 153 154 155 156 157 158 159
    """Defaults sort parameters must be passed to the list method, under the
    'sort_on' key.
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

    # We create a script to use as a list method, in this script, we will check
    # the sort_on parameter.
160
    list_method_id = 'ListBox_checkSortOnListMethod'
161 162 163 164 165
    createZODBPythonScript(
        portal.portal_skins.custom,
        list_method_id,
        'selection=None, sort_on=None, **kw',
r"""
166 167
if sort_on != [('title', 'ASC'), ('uid', 'ASC')]:
  raise AssertionError('sort_on is %r' % sort_on)
168 169 170 171 172
return []
""")
 
    # set the listbox to use this as list method
    listbox = portal.FooModule_viewFooList.listbox
173
    listbox.ListBox_setPropertyList(
174
      field_list_method = list_method_id,
175
      field_count_method = '',
176 177 178 179 180 181
      field_sort = 'title | ASC\n'
                   'uid | ASC',)
    
    # render the listbox, checks are done by list method itself
    request = get_request()
    request['here'] = portal.foo_module
182 183
    listbox.get_value('default', render_format='list', REQUEST=request)

184
  def test_03_DefaultParameters(self, quiet=quiet, run=run_all_test):
185 186 187 188 189 190 191 192 193 194 195 196 197
    """Defaults parameters are passed as keyword arguments to the list method
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

    # We create a script to use as a list method, in this script, we will check
    # the default parameter.
    list_method_id = 'ListBox_checkDefaultParametersListMethod'
    createZODBPythonScript(
        portal.portal_skins.custom,
        list_method_id,
        'selection=None, dummy_default_param=None, **kw',
"""
198 199 200
if dummy_default_param != 'dummy value':
  raise AssertionError('recieved wrong arguments: %s instead of "dummy value"'
                        % dummy_default_param )
201 202 203 204 205 206 207
return []
""")
 
    # set the listbox to use this as list method
    listbox = portal.FooModule_viewFooList.listbox
    listbox.ListBox_setPropertyList(
      field_list_method = list_method_id,
208
      field_count_method = '',
209 210 211 212 213 214 215
      field_default_params = 'dummy_default_param | dummy value',)
    
    # render the listbox, checks are done by list method itself
    request = get_request()
    request['here'] = portal.foo_module
    listbox.get_value('default', render_format='list', REQUEST=request)

216
  def test_04_UnicodeParameters(self, quiet=0, run=run_all_test):
217
    """Unicode properties are handled. 
218 219 220
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()
221 222
    
    # We create a script to use as a list method
223 224 225 226
    list_method_id = 'ListBox_ParametersListMethod'
    createZODBPythonScript(
        portal.portal_skins.custom,
        list_method_id,
227 228
        'selection=None, **kw',
        """return [context.asContext(alternate_title = u'\xe9lisa')]""")
229 230
 
    # set the listbox to use this as list method
231
    listbox = portal.FooModule_viewFooList.listbox
232 233
    listbox.ListBox_setPropertyList(
      field_list_method = list_method_id,
234
      field_count_method = '',
235 236 237 238
      field_columns = ['alternate_title | Alternate Title',],)
    
    request = get_request()
    request['here'] = portal.foo_module
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    try:
      listbox.get_value('default', render_format='list', REQUEST=request)
    except UnicodeError, e:
      self.fail('Rendering failed: %s' % e)

  def test_05_EditSelectionWithFileUpload(self, quiet=quiet, run=run_all_test):
    """Listbox edits selection with request parameters. Special care must be
    taken for FileUpload objects that cannot be pickled, thus cannot be stored
    in the ZODB.
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()
    listbox = portal.FooModule_viewFooList.listbox
    # XXX isn't Selection automatically created ?
    portal.portal_selections.setSelectionFor(
          listbox.get_value('selection_name'), Selection())

    request = get_request()
    request['here'] = portal.foo_module
    request.form['my_file_upload'] = FileUpload(DummyFieldStorage())
259
    listbox.get_value('default', render_format='list', REQUEST=request)
260
    try:
261
      transaction.commit()
262 263 264
    except TypeError, e:
      self.fail('Unable to commit transaction: %s' % e)

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  def test_06_LineFields(self, quiet=0, run=run_all_test):
    """
       Line Fields are able to render a list parameter in the form
       of lines. The same behaviour is expected for Line Fields used
       in ListBox objects.
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

    # Reset listbox properties
    listbox = portal.FooModule_viewFooList.listbox
    listbox.ListBox_setPropertyList(
      field_list_method = 'portal_catalog',
      field_columns = ['subject_list | Subjects',],
      field_editable_columns = ['subject_list | Subjects',],
    )

    # Create an new empty object with a list property
    foo_module = portal.foo_module
    word = 'averycomplexwordwhichhaslittlechancetoexistinhtml'
    o = foo_module.newContent(subject_list = [word])

    # Make sure that word is the subject list
    self.assertEqual(word in o.getSubjectList(), True)

    # Reindex
    o.immediateReindexObject()

    # Render the module in html
    request = get_request()
    request['here'] = portal.foo_module
    rendered_listbox = listbox.render(REQUEST=request)

    # Make sure that word is there
    self.assertEqual(rendered_listbox.find(word) > 0, True)

Nicolas Dumazet's avatar
Nicolas Dumazet committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  def testCellKeywordInProxifiedListboxColumn(self):
    """
    Test that cell keyword is correctly interpreted when used in TALES
    to render a cell of a ListBox.
    First use cell in the ProxyField context, then use it in the listbox_xxx
    context
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

    form = portal.Foo_viewListBoxProxyField
    portal.foo_module.FooModule_createObjects()
    here = portal.foo_module['0']
    here.Foo_createObjects()

    request = get_request()
    request['here'] = here

    transaction.commit()

    listbox_title_column = form.listbox_title

    self.assertTrue(listbox_title_column.is_delegated('default'))
    self.assertEquals(listbox_title_column.get_recursive_tales('default')._text,
                      'python: cell.getTitle()')
    listboxline_list = form.listbox.get_value('default', render_format = 'list',
                                              REQUEST = request)
    first_item = dict(listboxline_list[1].getColumnItemList())
    self.assertEquals(first_item['title'], 'Title 0')

    # Use "cell" locally
    listbox_title_column.manage_tales_surcharged_xmlrpc(
        dict(default=TALESMethod('python: cell.getTitle() + " local"')))

    listboxline_list = form.listbox.get_value('default', render_format = 'list',
                                              REQUEST = request)
    first_item = dict(listboxline_list[1].getColumnItemList())
    self.assertEquals(first_item['title'], 'Title 0 local')

340
  def _helperExtraAndCssInListboxLine(self, field_type, editable):
341
    """
342 343 344 345 346 347 348 349 350 351
    Create a listbox_xxx field, in the hidden group, that defines
    identifiable CSS classes and extra properties.
      - field_type: type of the field which is created
      - editable: boolean, defines if the field should be defined as editable

    Render the field in the listbox, and check that CSS and extra are
    present in the rendered HTML

    Field names and Ids are generated to be unique for each
    (field_type, editable) entry.
352 353 354 355
    """
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

356 357 358 359 360
    field_name = field_type.lower()
    if editable:
      field_name += '_editable'
    field_id = 'listbox_' + field_name

361 362 363 364
    # Reset listbox properties
    listbox = portal.FooModule_viewFooList.listbox
    listbox.ListBox_setPropertyList(
      field_list_method = 'portal_catalog',
365
      field_columns = ['%s | Check extra' % field_name,],
366 367 368
    )

    form = portal.FooModule_viewFooList
369 370 371 372 373 374 375 376 377 378 379 380
    form.manage_addField(field_id, field_name, field_type)
    field = getattr(form, field_id)

    word = '%s_dummy_%%s_to_check_for_in_listbox_test' % field_name
    extra = word % 'extra'
    css_class = word % 'css_class'
    field.values['extra'] = "alt='%s'" % extra
    field.values['css_class'] = css_class
    field.values['default'] = '42'
    field.values['editable'] = editable
    form.groups['bottom'].remove(field_id)
    form.groups['hidden'].append(field_id)
381 382 383 384 385 386 387 388 389 390 391 392 393

    # Create an new empty object with a list property
    foo_module = portal.foo_module
    o = foo_module.newContent()

    # Reindex
    o.immediateReindexObject()

    # Render the module in html
    request = get_request()
    request['here'] = portal.foo_module
    rendered_listbox = listbox.render(REQUEST=request)

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    if editable:
      editable_text = 'An editable'
    else:
      editable_text = 'A non-editable'
    error_msg = "%s %s used as a listbox cell does not render properly the " \
        "'%%s' property" % (editable_text, field_type)

    # Make sure that the extras and css_classes are rendered
    self.assertTrue(extra in rendered_listbox, error_msg % 'extra')
    self.assertTrue(css_class in rendered_listbox, error_msg % 'css_class')

  def test_07_ExtraAndCssFieldsInIntegerField(self, quiet=0, run=run_all_test):
    """
      Check that css_class and extra fields are rendered when used in a
      listbox_xxx line, using IntegerField for the check.
    """
    self._helperExtraAndCssInListboxLine("IntegerField", True)
    self._helperExtraAndCssInListboxLine("IntegerField", False)

  def test_08_ExtraAndCssFieldsInLinesField(self, quiet=0, run=run_all_test):
    """
      Check that css_class and extra fields are rendered when used in a
      listbox_xxx line, using LinesField for the check.
    """
    self._helperExtraAndCssInListboxLine("LinesField", True)
    self._helperExtraAndCssInListboxLine("LinesField", False)
420

421
  def test_09_editablePropertyConfiguration(self):
422
    """
423 424 425
      Test editable behavior of delegated columns.
      A column is editable if and only if listbox_foo is editable AND foo is
      in the editable columns of the listbox.
426 427 428 429 430

      For example, if listbox_foo is defined as editable, without
      having column "foo" listed as editable in the listbox, the field should
      not be rendered as editable
    """
431 432 433 434 435 436 437
    self._helperEditableColumn(True, True, True)
    self._helperEditableColumn(False, False, False)
    self._helperEditableColumn(True, False, False)
    self._helperEditableColumn(False, True, False)

  def _helperEditableColumn(self, editable_in_listbox, editable_in_line,
      expected_editable):
438 439 440
    portal = self.getPortal()
    portal.ListBoxZuite_reset()

441 442 443 444
    field_name = 'editableproperty_%s_%s' \
                    % (editable_in_listbox, editable_in_line)
    field_name = field_name.lower()
    field_id = 'listbox_%s' % field_name
445 446 447

    # Reset listbox properties
    listbox = portal.FooModule_viewFooList.listbox
448
    kw = dict(
449 450 451
      field_list_method = 'portal_catalog',
      field_columns = ['%s | Check extra' % field_name,],
    )
452 453 454 455 456
    if editable_in_listbox:
      kw['field_editable_columns'] = '%s | Check extra' % field_name

    listbox.ListBox_setPropertyList(**kw)

457 458 459 460 461 462

    form = portal.FooModule_viewFooList
    form.manage_addField(field_id, field_name, "StringField")
    field = getattr(form, field_id)

    field.values['default'] = '42'
463
    field.values['editable'] = editable_in_line
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    form.groups['bottom'].remove(field_id)
    form.groups['hidden'].append(field_id)

    # Create an new empty object with a list property
    foo_module = portal.foo_module
    o = foo_module.newContent()

    # Reindex
    o.immediateReindexObject()

    # Render the module in html
    request = get_request()
    request['here'] = portal.foo_module
    rendered_listbox = listbox.render(REQUEST=request)

    html = etree.HTML(rendered_listbox)
    # When a StringField is editable, it is rendered as an input
    # with name: "field_%(field_id)s_%(object_id)s"
    editable_field_list = html.xpath(
                            '//input[starts-with(@name, $name)]',
                            name='field_%s_' % field_id,
                          )
486 487 488 489

    msg = "editable_in_listbox: %s, editable_in_line: %s" \
            % (editable_in_listbox, editable_in_line)
    self.assertEquals(len(editable_field_list) == 1, expected_editable, msg)
490

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  def test_ObjectSupport(self):
    # make sure listbox supports rendering of simple objects
    # the only requirement is that objects have a `uid` attribute which is a
    # string starting by new_ (a convention to prevent indexing of objects).
    portal = self.getPortal()
    list_method_id = 'DummyListMethodId'
    portal.ListBoxZuite_reset()
    form = portal.FooModule_viewFooList
    listbox = form.listbox
    listbox.ListBox_setPropertyList(
      field_list_method = list_method_id,
      field_count_method = '',
      field_editable_columns = ['title | title'],
      field_columns = ['title | Title',],)
    form.manage_addField('listbox_title', 'Title', 'StringField')
    
    createZODBPythonScript(
        portal.portal_skins.custom,
        list_method_id,
        'selection=None, **kw',
        "from Products.PythonScripts.standard import Object\n"
        "return [Object(uid='new_', title='Object Title')]")
    
    request = get_request()
    request['here'] = portal.foo_module
    line_list = [l for l in listbox.get_value('default',
                               render_format='list',
                               REQUEST=request) if l.isDataLine()]
    self.assertEquals(1, len(line_list))
    self.assertEquals('Object Title', line_list[0].getColumnProperty('title'))
    html = listbox.render(REQUEST=request)
    self.failUnless('Object Title' in html, html)

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  def test_ProxyFieldRenderFormatLines(self):
    # tests that listbox default value in render_format=list mode is
    # compatible with proxy field.
    portal = self.getPortal()
    portal.ListBoxZuite_reset()
    form = portal.FooModule_viewFooList
    listbox = form.listbox
    listbox.ListBox_setPropertyList(
      field_list_method='contentValues',
      field_columns=['listbox_value | Title',],)
    
    # create a form, to store our proxy field inside
    portal._setObject('Test_view',
                      ERP5Form('Test_view', 'View'))
    portal.Test_view.manage_addField('listbox', 'listbox', 'ProxyField')
    proxy_field = portal.Test_view.listbox
    proxy_field.manage_edit_xmlrpc(dict(
            form_id=form.getId(), field_id='listbox',
            columns=[('proxy_value', 'Proxy')]))

    # this proxy field will not delegate its "columns" value
    proxy_field._surcharged_edit(dict(columns=[('proxy_value', 'Proxy')]),
                                ['columns'])
    
    request = get_request()
    request['here'] = portal.foo_module
    line_list = proxy_field.get_value('default',
                      render_format='list', REQUEST=request)
    self.failUnless(isinstance(line_list, list))

    title_line = line_list[0]
    self.failUnless(title_line.isTitleLine())

    # title of columns is the value overloaded by the proxy field.
    self.assertEquals([('proxy_value', 'Proxy')],
                      title_line.getColumnItemList())


Jérome Perrin's avatar
Jérome Perrin committed
562 563 564 565
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestListBox))
  return suite
566