Example #1
0
  def test_05_SomeHours(self, quiet=0, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test Some Hours'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    right_first_date = DateTime(self.date_format  % (2006,10,6,15,00,00))
    now = DateTime(self.date_format               % (2006,10,6,15,00,00))
    right_second_date = DateTime(self.date_format % (2006,10,6,21,00,00))
    right_third_date = DateTime(self.date_format  % (2006,10,7,06,00,00))
    right_fourth_date = DateTime(self.date_format % (2006,10,7,10,00,00))
    alarm = self.newAlarm(enabled=True)
    hour_list = (6,10,15,21)
    alarm.setPeriodicityStartDate(now)
    alarm.setPeriodicityHourList(hour_list)
    transaction.commit()
    self.tic()
    self.assertEquals(alarm.getAlarmDate(),right_first_date)
    alarm.setNextAlarmDate(current_date=right_first_date)
    self.assertEquals(alarm.getAlarmDate(),right_second_date)
    alarm.setNextAlarmDate(current_date=right_second_date)
    self.assertEquals(alarm.getAlarmDate(),right_third_date)
    alarm.setNextAlarmDate(current_date=right_third_date)
    self.assertEquals(alarm.getAlarmDate(),right_fourth_date)
  def test_01_relationFieldToInaccessibleObject(self, quiet=quiet, run=run_all_test):
    """
      This test checks if a form can be viewed when it contains a RelationStringField which
      links to an object the user is not authorized to view.

      This fails for now. A proposed patch solving this problem is here:
      http://svn.erp5.org/experimental/FSPatch/Products/ERP5Form/ERP5Form_safeRelationField.diff?view=markup

      This problem can happen for example in the following situation:
      - a user is a member of a project P team, so he can view P
      - the user creates a project-related document and leaves it in "draft" state
      - the user quits the project P team
      Then the user can not view the project, but still can view his document as he is the owner.
      An attempt to view the document form would raise Unauthorized.
    """
    self.login()
    if not run: return
    if not quiet:
      message = 'test_01_relationFieldToInaccessibleObject'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', 0, message)
    sequence_list = SequenceList()
    sequence_string = '\
                       CreateObjects \
                       CreateTestFoo \
                       Tic \
                       AccessFoo \
                       ChangeCategorySecurity \
                       AccessFoo \
                       ResetCategorySecurity \
                       AccessFoo \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)
Example #3
0
 def test_01_CheckOpenCounterDateTwiceFail(self, quiet=QUIET, run=RUN_ALL_TEST):
     """
   Test that opening a counter date when there is a counter date opened fails.
 """
     if not run:
         return
     if not quiet:
         message = "Check open CounterDate twice fails"
         ZopeTestCase._print("\n%s " % message)
         LOG("Testing... ", 0, message)
     self.openCounterDate(site=self.paris, id="counter_date_1")
     self.tic()
     self.openCounterDate(site=self.paris, id="counter_date_2", open=0)
     # open counter date and counter
     self.assertRaises(
         ValidationFailed,
         self.workflow_tool.doActionFor,
         self.counter_date_2,
         "open_action",
         wf_id="counter_date_workflow",
     )
     # get workflow history
     workflow_history = self.workflow_tool.getInfoFor(
         ob=self.counter_date_2, name="history", wf_id="counter_date_workflow"
     )
     # check its len is 2
     msg = workflow_history[-1]["error_message"]
     self.assertTrue("there is already a counter date opened" in "%s" % (msg,))
Example #4
0
 def test_05_checkBackupWithTrashSubObjects(self, quiet=quiet, run=run_all_test):
   """
   Test we can backup a tree like this :
   base_category/trash_folder/category
   """
   if not run: return
   if not quiet:
     message = 'Test Check Backup With Trash Sub Object'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ', 0, message)
   sequence_list = SequenceList()
   sequence_string = '\
                      CheckTrashToolExists  \
                      CreateTrashBin \
                      CheckTrashBinIndexable \
                      AddBaseCategory \
                      AddCategories \
                      AddSubCategories \
                      Tic \
                      BackupObjectsWithSave \
                      Tic \
                      CheckObjectBackupWithoutSubObjects \
                      BackupSubCategories \
                      '
   sequence_list.addSequenceString(sequence_string)
   sequence_list.play(self, quiet=quiet)
 def test_01_CheckOpenCounterDateTwiceFail(self, quiet=QUIET, run=RUN_ALL_TEST):
   """
     Test that opening a counter date when there is a counter date opened fails.
   """
   if not run:
     return
   if not quiet:
     message = 'Check open CounterDate twice fails'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ', 0, message)
   self.openCounterDate(site=self.paris, id='counter_date_1')
   transaction.commit()
   self.tic()
   self.openCounterDate(site=self.paris, id='counter_date_2', open=0)
   # open counter date and counter
   self.assertRaises(ValidationFailed,
                    self.workflow_tool.doActionFor,
                    self.counter_date_2, 'open_action',
                    wf_id='counter_date_workflow')
   # get workflow history
   workflow_history = self.workflow_tool.getInfoFor(
          ob=self.counter_date_2, name='history', wf_id='counter_date_workflow')
   # check its len is 2
   msg = workflow_history[-1]['error_message']
   self.assertTrue('there is already a counter date opened' in "%s" %(msg, ))
    def makeEntries(self):
        #Test for adding category
        ZopeTestCase._print('Try to add categories ... \n')
        catf = self.blog.getCategoryFolder()
        cat_names = [ 'cat%d' % x for x in range(1,10) ]
        for catname in cat_names:
            catf.invokeFactory('COREBlogCategory',id=catname)
        #Test for category creation
        for catname in cat_names:
            self.failUnless(hasattr(catf, catname),
                        'Category %s not found' %catname)

        #Try to add entry
        ZopeTestCase._print('Try to add entries ... \n')
        cfold = self.blog.getCategoryFolder()
        for cnt in range(0,len(entry_data)):
            new_id = 'entry_%d' % cnt
            self.blog.invokeFactory('COREBlogEntry',new_id)
            self.failUnless(hasattr(self.blog, new_id),
                        'Entry %s not found' %catname)
            ent = self.blog[new_id]
            ent.setBody(entry_data[cnt][0],mimetype='text/structured')
            ent.setEntry_categories(\
                [str(cfold[x].getInternal_id()) for x in entry_data[cnt][1]])
            ent.setEffectiveDate(DateTime(entry_data[cnt][2]))
            ent.indexObject()
  def test_01_checkPasswordTool(self, quiet=quiet, run=run_all_test):
    if not run: return
    if not quiet:
      message = 'Test Password Tool'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', 0, message)
    sequence_list = SequenceList()
    sequence_string = 'CheckPasswordToolExists '  \
                      'AddUser Tic ' \
                      'Logout ' \
                      'CheckUserLogin CheckUserNotLoginWithBadPassword ' \
                      'TryLostPasswordWithBadUser Tic ' \
                      'CheckNoMailSent ' \
                      'GoToBadRandomAddress Tic ' \
                      'CheckUserLogin CheckUserNotLoginWithBadPassword ' \
                      'LostPassword Tic ' \
                      'CheckMailSent GoToRandomAddress Tic '  \
                      'CheckUserLoginWithNewPassword ' \
                      'CheckUserNotLoginWithFormerPassword ' \
                      'GoToRandomAddressTwice Tic ' \
                      'CheckUserLoginWithNewPassword ' \
                      'CheckUserNotLoginWithFormerPassword ' \

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)
Example #8
0
 def test_03_EveryHour(self, quiet=0, run=run_all_test):
   if not run: return
   if not quiet:
     message = 'Test Every Hour'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ',0,message)
   alarm = self.newAlarm(enabled=True)
   now = DateTime()
   date = addToDate(now, day=2)
   alarm.setPeriodicityStartDate(date)
   alarm.setPeriodicityHourFrequency(1)
   self.tic()
   alarm.setNextAlarmDate(current_date=now)
   self.assertEqual(alarm.getAlarmDate(), date)
   LOG(message + ' now :',0,now)
   now = addToDate(now,day=2)
   LOG(message + ' now :',0,now)
   alarm.setNextAlarmDate(current_date=now)
   next_date = addToDate(date,hour=1)
   self.assertEqual(alarm.getAlarmDate(),next_date)
   now = addToDate(now,hour=1,minute=5)
   alarm.setNextAlarmDate(current_date=now)
   next_date = addToDate(next_date,hour=1)
   self.assertEqual(alarm.getAlarmDate(),next_date)
   # check if manual invoking does not break getAlarmDate() result.
   alarm.activeSense()
   self.assertEqual(alarm.getAlarmDate(),next_date)
Example #9
0
 def test_04_Every3Hours(self, quiet=0, run=run_all_test):
   if not run: return
   if not quiet:
     message = 'Test Every 3 Hours'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ',0,message)
   alarm = self.newAlarm(enabled=True)
   now = DateTime().toZone('UTC')
   hour_to_remove = now.hour() % 3
   now = addToDate(now,hour=-hour_to_remove)
   date = addToDate(now,day=2)
   alarm.setPeriodicityStartDate(date)
   alarm.setPeriodicityHourFrequency(3)
   self.tic()
   alarm.setNextAlarmDate(current_date=now)
   self.assertEqual(alarm.getAlarmDate(),date)
   LOG(message + ' now :',0,now)
   now = addToDate(now,day=2)
   LOG(message + ' now :',0,now)
   alarm.setNextAlarmDate(current_date=now)
   next_date = addToDate(date,hour=3)
   self.assertEqual(alarm.getAlarmDate(),next_date)
   now = addToDate(now,hour=3,minute=7,second=4)
   alarm.setNextAlarmDate(current_date=now)
   next_date = addToDate(next_date,hour=3)
   self.assertEqual(alarm.getAlarmDate(),next_date)
Example #10
0
 def test_listActionInListbox(self):
   # check all list_action in listboxes
   skins_tool = self.portal.portal_skins
   error_list = []
   for form_path, form in skins_tool.ZopeFind(
             skins_tool, obj_metatypes=['ERP5 Form'], search_sub=1):
     for field in self.getFieldList(form, form_path):
       if field.getRecursiveTemplateField().meta_type == 'ListBox':
         list_action = field.get_value("list_action")
         if list_action and list_action != 'list': # We assume that 'list'
                                                   # list_action exists
           if isinstance(list_action, str):
             # list_action can be a fully qualified URL, we care for last part of it
             list_action = list_action.split('/')[-1].split('?')[0]
             try:
               method = self.portal.restrictedTraverse(list_action)
             except KeyError:
               method = None
             if method is None:
               # list_action can actually exists but not in current skin, check if it can be found in portal_skins
               found_list_action_list = skins_tool.ZopeFind(skins_tool, obj_ids=[list_action], search_sub=1)
               if found_list_action_list:
                 method = found_list_action_list[0][1]
                 ZopeTestCase._print("List action %s for %s is not part of current skin but do exists in another skin folder.\n" % (list_action, form_path))
           else:
             method = list_action
           if not callable(method):
             error_list.append('Form %s/%s : list_action "%s" is not callable.'\
                 % (form_path, field.id, list_action))
   self.assert_(not len(error_list), '\n'.join(error_list))
Example #11
0
 def tearDown(self):
   '''Tears down the fixture. Do not override,
      use the hooks instead.
   '''
   if not int(os.environ.get('erp5_save_data_fs', 0)):
     # Drop remaining activities if some of them failed.
     # However, we should not do more activity cleaning, because properly
     # written unit tests should not leave unprocessed activity messages.
     # And the user may want to analyse the result of a failed unit test,
     # so we do nothing in persistent mode (--save).
     try:
       portal_activities = self.portal.portal_activities
       message_list = portal_activities.getMessageList()
     except StandardError: # AttributeError, TransactionFailedError ...
       pass
     else:
       for m in message_list:
         if m.processing_node < -1:
           self.abort()
           count = portal_activities.countMessage()
           portal_activities.manageClearActivities()
           self.commit()
           ZopeTestCase._print(' (dropped %d left-over activity messages) '
                               % count)
           break
   PortalTestCase.tearDown(self)
Example #12
0
def fortify():
  '''Add some extra checks that we don't have at runtime, not to slow down the
  system.
  '''
  # check that we don't store persistent objects in cache
  from Products.ERP5Type.CachePlugins.BaseCache import CacheEntry
  CacheEntry.__original_init__ = CacheEntry.__init__
  def __init__(self, value, *args, **kw):
    # this will raise TypeError if you try to cache a persistent object
    dumps(value)
    return self.__original_init__(value, *args, **kw)
  CacheEntry.__init__ = __init__

  # randomize priorities of activities in a deterministic way
  seed = os.environ.get("random_activity_priority")
  if seed is not None:
    ZopeTestCase._print("RNG seed for priorities of activities is %r\n" % seed)
    rng = random.Random(seed)
    from Products.CMFActivity.ActivityTool import Message
    Message__init__ = Message.__init__
    def __init__(self, url, oid, active_process, active_process_uid,
                 activity_kw, *args, **kw):
      activity_kw['priority'] = rng.randint(-128, 127)
      Message__init__(self, url, oid, active_process, active_process_uid,
                      activity_kw, *args, **kw)
    Message.__init__ = __init__
Example #13
0
 def test_12_Every5Minutes(self, quiet=0, run=run_all_test):
   if not run: return
   if not quiet:
     message = 'Test Every 5 Minutes'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ',0,message)
   alarm = self.newAlarm(enabled=True)
   now = DateTime()
   minute_to_remove = now.minute() % 5
   now = addToDate(now,minute=-minute_to_remove)
   date = addToDate(now,day=2)
   alarm.setPeriodicityStartDate(date)
   alarm.setPeriodicityMinuteFrequency(5)
   self.tic()
   alarm.setNextAlarmDate(current_date=now)
   self.assertEqual(alarm.getAlarmDate(),date)
   LOG(message + ' now :',0,now)
   now = addToDate(now,day=2)
   LOG(message + ' now :',0,now)
   alarm.setNextAlarmDate(current_date=now)
   next_date = addToDate(date,minute=5)
   self.assertEqual(alarm.getAlarmDate(),next_date)
   now = addToDate(now,minute=5,second=14)
   alarm.setNextAlarmDate(current_date=now)
   next_date = addToDate(next_date,minute=5)
   self.assertEqual(alarm.getAlarmDate(),next_date)
Example #14
0
  def test_16_uncatalog(self, quiet=0, run=run_all_test):
    """
    Check that deleting an alarm uncatalogs it.
    """
    if not run: return
    if not quiet:
      message = 'Test Uncatalog'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', 0, message)
    alarm = self.newAlarm(enabled=True)
    self.tic()

    now = DateTime()
    date = addToDate(now, day=1)
    alarm.setPeriodicityStartDate(date)
    self.tic()
    self.assertEqual(alarm.getAlarmDate(), date)

    # This should not do change the alarm date
    alarm.setNextAlarmDate(current_date=now)
    self.tic()
    self.assertEqual(alarm.getAlarmDate(), date)

    # Delete the alarm
    a_tool = self.getAlarmTool()
    alarm_uid = alarm.getUid()
    a_tool.manage_delObjects(uids=[alarm_uid])
    self.tic()
    # Check that related entry was removed
    sql_connection = self.getSQLConnection()
    sql = 'select * from alarm where uid=%s' % alarm_uid
    result = sql_connection.manage_test(sql)
    self.assertEqual(0, len(result))
 def test_02_CheckOpenCounterDateWithOtherDateFail(self, quiet=QUIET, run=RUN_ALL_TEST):
   """
     Test that opening a counter date on a non-current date fails.
   """
   if not run:
     return
   if not quiet:
     message = 'Check open CounterDate on non-current date fails'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ', 0, message)
   def openAndTest(id, date):
     self.openCounterDate(site=self.paris, id=id, date=date, open=0)
     # open counter date and counter
     counter_date = getattr(self, id)
     self.assertRaises(ValidationFailed,
                      self.workflow_tool.doActionFor,
                      counter_date, 'open_action',
                      wf_id='counter_date_workflow')
     # get workflow history
     workflow_history = self.workflow_tool.getInfoFor(
            ob=counter_date, name='history', wf_id='counter_date_workflow')
     # check its len is 2
     msg = workflow_history[-1]['error_message']
     self.assertTrue('the date is not today' in "%s" %(msg, ))
   now = DateTime()
   # Future
   openAndTest('1', now + 2) # Just in case midnight passes between "now" calculation and validation, add 2 instead of 1
   # Past
   openAndTest('2', now - 1)
Example #16
0
  def test_07a_Every4DaysSomeHours(self, quiet=0, run=run_all_test):
    """- every 4 days at 14 and 15 and 17"""
    if not run: return
    if not quiet:
      message = 'Every 4 Days Some Hours'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ',0,message)

    right_first_date = DateTime(self.date_format % (2006,10,7,13,00,00))
    right_second_date = DateTime(self.date_format  % (2006,10,8,14,00,00))
    right_third_date = DateTime(self.date_format  % (2006,10,8,15,00,00))
    right_fourth_date = DateTime(self.date_format  % (2006,10,8,17,00,00))
    right_fifth_date = DateTime(self.date_format  % (2006,10,12,14,00,00))
    alarm = self.newAlarm(enabled=True)
    alarm.setPeriodicityStartDate(right_first_date)
    alarm.setPeriodicityDayFrequency(4)
    alarm.setPeriodicityHourList((14,15,17))
    self.tic()
    self.assertEqual(alarm.getAlarmDate(),right_first_date)
    alarm.setNextAlarmDate(current_date=right_first_date)
    self.assertEqual(alarm.getAlarmDate(),right_second_date)
    alarm.setNextAlarmDate(current_date=right_second_date)
    self.assertEqual(alarm.getAlarmDate(),right_third_date)
    alarm.setNextAlarmDate(current_date=right_third_date)
    self.assertEqual(alarm.getAlarmDate(),right_fourth_date)
    alarm.setNextAlarmDate(current_date=right_fourth_date)
    self.assertEqual(alarm.getAlarmDate(),right_fifth_date)
Example #17
0
  def test_04_WebSectionAuthorizationForcedForDefaultDocument(self, quiet=quiet, run=run_all_test):
    """ Check that when a Web Section contains a default document not accessible by user we have a chance to
        require user to login.
        Whether or not an user will login is controlled by a property on Web Section (authorization_forced).
    """
    if not run: return
    if not quiet:
      message = '\ntest_04_WebSectionAuthorizationForcedForDefaultDocument'
      ZopeTestCase._print(message)
    request = self.app.REQUEST
    website = self.setupWebSite()
    websection = self.setupWebSection()
    web_page_reference = 'default-document-reference'
    web_page_en = self.portal.web_page_module.newContent(
                                      portal_type = 'Web Page',
                                      language = 'en',
                                      reference = web_page_reference)
    # this way it's not viewable by anonymous and we can test
    web_page_en.releaseAlive()
    websection.setAggregateValue(web_page_en)
    websection.setAuthorizationForced(1)
    self.tic()

    # make sure that getDefaultDocumentValue() will return the same document for logged in user
    # if default document is accessible
    self.assertEqual(web_page_en.getUid(),
                           websection.getDefaultDocumentValue().getUid())

    # check Unauthorized exception is raised for anonymous when authorization_forced is set
    self.logout()
    self.assertEqual(None,  websection.getDefaultDocumentValue())
    self.assertRaises(Unauthorized,  websection)

    # Anonymous User should not get Unauthorized when authorization_forced is not set
    self.login()
    websection.setAuthorizationForced(0)
    self.tic()

    self.logout()
    self.assertEqual(None,  websection.getDefaultDocumentValue())
    try:
      websection()
    except Unauthorized:
      self.fail("Web Section should not prompt user for login.")

    self.login()
    web_page_list = []
    for iteration in range(0, 10):
      web_page =self.getPortal().web_page_module.newContent(portal_type = 'Web Page',
                                                            reference = "%s_%s" % (web_page_reference, iteration),
                                                            language = 'en',)
      web_page.publish()
      self.tic()
      self.commit()
      web_page_list.append(web_page)
    websection.setAggregateValueList(web_page_list)
    self.tic()
    self.commit()
    self.assertEqual(5, len(websection.getDocumentValueList(limit=5)))
Example #18
0
 def logMessage(self, msg, tab=0):
   """
   Log a message.
   """
   if tab:
     msg = '  %s' % msg
   ZopeTestCase._print('\n%s' % msg)
   LOG('testResource.play', 0, msg)
    def test_000folders(self):
        #Test for standard folders existance
        ZopeTestCase._print('Test for standard folders ... \n')

        self.failUnless(comment_folder_id in self.blog.objectIds())
        self.failUnless(catetory_folder_id in self.blog.objectIds())
        self.failUnless(stuff_folder_id in self.blog.objectIds())
        self.failUnless(images_folder_id in self.blog.objectIds())
Example #20
0
 def test_01_HasEverything(self, quiet=0, run=run_all_test):
   # Test if portal_alarms was created
   if not run: return
   if not quiet:
     ZopeTestCase._print('\nTest Has Everything ')
     LOG('Testing... ',0,'testHasEverything')
   self.assertNotEquals(self.portal._getOb('portal_alarms', None), None)
   self.assertNotEquals(self.portal.portal_types.getTypeInfo('Alarm Tool'), None)
Example #21
0
 def loadPromise(self):
   """ Create promise configuration file and load it into configuration
   """
   promise_path = os.path.join(instancehome, "promise.cfg")
   ZopeTestCase._print('Adding Promise at %s...\n' % promise_path)
   _createTestPromiseConfigurationFile(promise_path)
   config.product_config["/%s" % self.getPortalName()] = \
      {"promise_path": promise_path}
Example #22
0
 def _callSetUpOnce(self):
   setup_once = getattr(self, 'setUpOnce', None)
   if setup_once is not None and \
          not getattr(self.portal, 'set_up_once_called', 0):
     self.portal.set_up_once_called = 1
     ZopeTestCase._print('Executing setUpOnce ... ')
     start = time.time()
     setup_once()
     ZopeTestCase._print('done (%.3fs)\n' % (time.time() - start))
Example #23
0
 def setupPloneFormMailerTestCase(app, quiet=0):
     get_transaction().begin()
     _start = time.time()
     if not quiet:
         ZopeTestCase._print('Adding PloneFormMailer ... ')
     app.portal.portal_quickinstaller.installProduct('PloneFormMailer')
     get_transaction().commit()
     if not quiet:
         ZopeTestCase._print('done (%.3fs)\n' % (time.time()-_start,))
def printAndLog(msg):
    """
  A utility function to print a message
  to the standard output and to the LOG
  at the same time
  """
    msg = str(msg)
    ZopeTestCase._print("\n " + msg)
    LOG("Testing... ", 0, msg)
Example #25
0
  def test_03_LatestContent(self, quiet=quiet, run=run_all_test):
    """ Test latest content for a Web Section. Test different use case like languaeg, workflow state.
   """
    if not run: return
    if not quiet:
      message = '\ntest_03_LatestContent'
      ZopeTestCase._print(message)
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    portal_categories = portal.portal_categories
    publication_section_category_id_list = ['documentation',  'administration']
    for category_id in publication_section_category_id_list:
      portal_categories.publication_section.newContent(portal_type = 'Category',
                                                                             id = category_id)
    #set predicate on web section using 'publication_section'
    websection.edit(membership_criterion_base_category = ['publication_section'],
                            membership_criterion_category=['publication_section/%s'
                                                                              %publication_section_category_id_list[0]])
    transaction.commit()
    self.tic()

    self.assertEquals(0,  len(websection.getDocumentValueList()))
    # create pages belonging to this publication_section 'documentation'
    web_page_en = portal.web_page_module.newContent(portal_type = 'Web Page',
                                                 language = 'en',
                                                 publication_section_list=publication_section_category_id_list[:1])
    web_page_en.publish()
    transaction.commit()
    self.tic()
    self.assertEquals(1,  len(websection.getDocumentValueList(language='en')))
    self.assertEquals(web_page_en,  websection.getDocumentValueList(language='en')[0].getObject())

    # create pages belonging to this publication_section 'documentation' but for 'bg' language
    web_page_bg = portal.web_page_module.newContent(portal_type = 'Web Page',
                                                 language = 'bg',
                                                 publication_section_list=publication_section_category_id_list[:1])
    web_page_bg.publish()
    transaction.commit()
    self.tic()
    self.assertEquals(1,  len(websection.getDocumentValueList(language='bg')))
    self.assertEquals(web_page_bg,  websection.getDocumentValueList(language='bg')[0].getObject())

    # reject page
    web_page_bg.reject()
    transaction.commit()
    self.tic()
    self.assertEquals(0,  len(websection.getDocumentValueList(language='bg')))

    # publish page and search without a language (by default system should return 'en' docs only)
    web_page_bg.publish()
    transaction.commit()
    self.tic()
    self.assertEquals(1,  len(websection.getDocumentValueList()))
    self.assertEquals(web_page_en,  websection.getDocumentValueList()[0].getObject())
Example #26
0
 def getFieldList(self, form, form_path):
   try:
     for field in form.get_fields(include_disabled=1):
       if field.getTemplateField() is not None:
         try:
           if field.get_value('enabled'):
             yield field
         except Exception:
           yield field
   except AttributeError, e:
     ZopeTestCase._print("%s is broken: %s" % (form_path, e))
Example #27
0
 def test_14_NewActiveProcess(self, quiet=0, run=run_all_test):
   if not run: return
   if not quiet:
     message = 'Test New Active Process'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ',0,message)
   alarm = self.newAlarm(enabled=True)
   active_process = alarm.newActiveProcess()
   self.assertEqual('Active Process', active_process.getPortalType())
   self.assertEqual(alarm, active_process.getCausalityValue())
   self.tic()
   self.assertEqual(active_process, alarm.getLastActiveProcess())
Example #28
0
 def play(self, context, sequence=None, sequence_number=0, quiet=0):
   if not quiet:
     if self._played_index == 0:
       ZopeTestCase._print('\nStarting New Sequence %i... ' % sequence_number)
       LOG('Sequence.play', 0, 'Starting New Sequence %i... ' % sequence_number)
   if sequence is None:
     while self._played_index < len(self._step_list):
       self._step_list[self._played_index] \
       .play(context, sequence=self, quiet=quiet)
       # commit transaction after each step
       transaction.commit()
       self._played_index += 1
Example #29
0
 def test_20_UndefinedPeriodicityStartDate(self, quiet=0, run=run_all_test):
   """
   Test that getAlarmDate does not crash when PeriodicityStartDate is not set.
   """
   if not run: return
   if not quiet:
     message = 'Test undefined PeriodicityStartDate'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ',0,message)
   alarm = self.newAlarm(enabled=True)
   # Test sanity check.
   self.assertEqual(alarm.getPeriodicityStartDate(), None)
   # Actual test.
   self.assertEqual(alarm.getAlarmDate(), None)
Example #30
0
 def test_13_EveryMinute(self, quiet=0, run=run_all_test):
   if not run: return
   if not quiet:
     message = 'Test Every Minute'
     ZopeTestCase._print('\n%s ' % message)
     LOG('Testing... ',0,message)
   alarm = self.newAlarm(enabled=True)
   now = DateTime()
   date = addToDate(now,hour=2)
   alarm.setPeriodicityStartDate(now)
   alarm.setPeriodicityMinuteFrequency(1)
   self.tic()
   alarm.setNextAlarmDate(current_date=date)
   self.assertEqual(alarm.getAlarmDate(),date)
Example #31
0
    def _testPerformanceInDepth(self):
        """
        Check HBTreeFolder2 GET performance with the depth and the number of
        documents.
        """
        init_1 = dedent("""
        from Products.HBTreeFolder2.HBTreeFolder2 import HBTreeFolder2
        from Products.CMFDefault.File import File
        h_depth_1 = HBTreeFolder2()
        for i in xrange(%d):
            id = str(i)
            h_depth_1[id] = File(id)
        """)
        init_2 = dedent("""
        from Products.HBTreeFolder2.HBTreeFolder2 import HBTreeFolder2
        from Products.CMFDefault.File import File
        h_depth_2 = HBTreeFolder2()
        for i in xrange(10):
            for j in xrange(%d / 10):
                id = "-".join(map(str, (i,j)))
                h_depth_2[id] = File(id)
        """)
        init_3 = dedent("""
        from Products.HBTreeFolder2.HBTreeFolder2 import HBTreeFolder2
        from Products.CMFDefault.File import File
        h_depth_3 = HBTreeFolder2()
        for i in xrange(10):
            for j in xrange(10):
                for k in xrange(%d / (10 * 10)):
                    id = "-".join(map(str, (i, j, k)))
                    h_depth_3[id] = File(id)
        """)

        N = 1000
        # measure 100 times of each test with timeit()
        t1 = timeit.Timer("h_depth_1['555']", init_1 % N).timeit(100)
        t2 = timeit.Timer("h_depth_2['5-55']", init_2 % N).timeit(100)
        t3 = timeit.Timer("h_depth_3['5-5-5']", init_3 % N).timeit(100)
        ZopeTestCase._print("\nN = 1000\n")
        ZopeTestCase._print("L1=%s\tL2=%s\tL3=%s" % (t1, t2, t3))

        N = 10000 # The N is 10 times larger than the previous measurement
        t2_1 = timeit.Timer("h_depth_1['5555']", init_1 % N).timeit(100)
        t2_2 = timeit.Timer("h_depth_2['5-555']", init_2 % N).timeit(100)
        t2_3 = timeit.Timer("h_depth_3['5-5-55']", init_3 % N).timeit(100)
        ZopeTestCase._print("\nN = 10000\n")
        ZopeTestCase._print("L1'=%s\tL2'=%s\tL3'=%s" % (t2_1, t2_2, t2_3))

        N = 100000  # The N is 10 times larger than the pevious measurement
        t3_1 = timeit.Timer("h_depth_1['22222']", init_1 % N).timeit(100)
        t3_2 = timeit.Timer("h_depth_2['2-2222']", init_2 % N).timeit(100)
        t3_3 = timeit.Timer("h_depth_3['2-2-222']", init_3 % N).timeit(100)
        ZopeTestCase._print("\nN = 100000\n")
        ZopeTestCase._print("L1''=%s\tL2''=%s\tL3''=%s" % (t3_1, t3_2, t3_3))

        # These assert are should be True, but right now those are not passed

        # assert L2 is faster than L1, because the leaves are fewer than L1
        self.assertTrue(t1 > t2)
        self.assertTrue(t2_1 > t2_2)
        self.assertTrue(t3_1 > t3_2)

        # assert L3 is faster than L2, because the leaves are fewer than L1
        self.assertTrue(t2 > t3)
        self.assertTrue(t2_2 > t2_3)
        self.assertTrue(t3_2 > t3_3)
Example #32
0
  def test_19_ManualInvocation(self, quiet=0, run=run_all_test):
    """
    test if an alarm can be invoked directly by the user securely,
    and if the results are identical when allowed.
    """
    if not run: return
    if not quiet:
      message = 'Test manual invocation'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', 0, message)

    alarm = self.newAlarm()
    # Create script that generate active process
    sense_method_id = 'Alarm_setBogusLocalProperty'
    skin_folder_id = 'custom'
    skin_folder = self.portal.portal_skins[skin_folder_id]
    skin_folder.manage_addProduct['PythonScripts']\
        .manage_addPythonScript(id=sense_method_id)
    skin_folder[sense_method_id].ZPythonScript_edit('*args,**kw', 
          'context.setProperty("bogus", str(context.showPermissions()))')

    # update alarm properties
    alarm.edit(active_sense_method_id=sense_method_id,
               enabled=False)
    self.tic()

    # Make a normal user.
    uf = self.getPortal().acl_users
    uf._doAddUser('normal', '', ['Member', 'Auditor'], [])
    user = uf.getUserById('normal').__of__(uf)
    
    # Check the pre-conditions.
    self.assertEquals(alarm.getProperty('bogus', None), None)
    self.assertEquals(alarm.getEnabled(), False)
    sm = getSecurityManager()
    newSecurityManager(None, user)

    # Non-managers must not be able to invoke a disabled alarm.
    self.assertRaises(Unauthorized, alarm.activeSense)
    self.assertRaises(Unauthorized, alarm.activeSense, fixit=1)

    # Non-managers must not be able to invoke the automatic fixation.
    setSecurityManager(sm)
    alarm.setEnabled(True)
    self.assertEquals(alarm.getEnabled(), True)
    newSecurityManager(None, user)
    self.assertRaises(Unauthorized, alarm.activeSense, fixit=1)

    # Now, check that everybody can invoke an enabled alarm manually.
    setSecurityManager(sm)
    correct_answer = str(alarm.showPermissions())
    self.assertNotEquals(correct_answer, None)

    alarm.activeSense()
    self.tic()
    self.assertEquals(alarm.getProperty('bogus', None), correct_answer)
    alarm.setProperty('bogus', None)
    self.assertEquals(alarm.getProperty('bogus', None), None)

    newSecurityManager(None, user)
    alarm.activeSense()
    self.tic()
    self.assertEquals(alarm.getProperty('bogus', None), correct_answer)
    setSecurityManager(sm)
    alarm.setProperty('bogus', None)

    # Check that Manager can invoke an alarm freely.
    alarm.activeSense(fixit=1)
    self.tic()
    self.assertEquals(alarm.getProperty('bogus', None), correct_answer)
    alarm.setProperty('bogus', None)
    self.assertEquals(alarm.getProperty('bogus', None), None)

    alarm.setEnabled(False)
    self.assertEquals(alarm.getEnabled(), False)

    alarm.activeSense()
    self.tic()
    self.assertEquals(alarm.getProperty('bogus', None), correct_answer)
    alarm.setProperty('bogus', None)
    self.assertEquals(alarm.getProperty('bogus', None), None)

    alarm.activeSense(fixit=1)
    self.tic()
    self.assertEquals(alarm.getProperty('bogus', None), correct_answer)
    alarm.setProperty('bogus', None)
    self.assertEquals(alarm.getProperty('bogus', None), None)
Example #33
0
    def test_Archive(self, quiet=quiet, run=1):  #run_all_test):
        if not run: return
        if not quiet:
            message = 'Archive'
            ZopeTestCase._print('\n%s ' % message)
            LOG('Testing... ', 0, message)

        portal = self.getPortal()
        portal_category = self.getCategoryTool()
        portal_archive = self.getArchiveTool()
        portal_catalog = self.getCatalogTool()
        inventory_module = portal.getDefaultModule(
            portal_type="Inventory Module")
        # Create some objects
        self.base_category = portal_category.newContent(
            portal_type='Base Category', title="GreatTitle1")
        module = portal.getDefaultModule('Organisation')
        self.organisation = module.newContent(portal_type='Organisation',
                                              title="GreatTitle2")
        getInventory = self.getSimulationTool().getInventory
        self.mvt = self._makeMovement(
            quantity=100,
            stop_date=DateTime("2006/06/06"),
            simulation_state='delivered',
        )
        self.assertEqual(100, getInventory(node_uid=self.node.getUid()))
        self.assertEqual(
            len(self.folder.searchFolder(portal_type="Dummy Movement")), 1)

        # Create an inventory object
        self.inventory = self._makeInventory(date=DateTime("2006/06/15"))
        self.assertEqual(
            len(inventory_module.searchFolder(portal_type="Inventory")), 1)

        # Flush message queue
        self.tic()

        # Check well in catalog
        self.original_connection_id = 'erp5_sql_connection'
        self.original_deferred_connection_id = 'erp5_sql_deferred_connection'
        path_list = [
            self.organisation.getRelativeUrl(),
            self.inventory.getRelativeUrl()
        ]
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.original_connection_id)

        # Create new connectors for destination
        addSQLConnection = portal.manage_addProduct['ZMySQLDA'] \
          .manage_addZMySQLConnection
        self.new_connection_id = 'erp5_sql_connection1'
        db1, db2 = getExtraSqlConnectionStringList()[:2]
        addSQLConnection(self.new_connection_id, '', db1)
        new_connection = portal[self.new_connection_id]
        new_connection.manage_open_connection()
        # the deferred one
        self.new_deferred_connection_id = 'erp5_sql_connection2'
        addSQLConnection(self.new_deferred_connection_id, '', db1)
        new_deferred_connection = portal[self.new_deferred_connection_id]
        new_deferred_connection.manage_open_connection()

        # Create new connectors for archive
        self.archive_connection_id = 'erp5_sql_connection3'
        addSQLConnection(self.archive_connection_id, '', db2)
        archive_connection = portal[self.archive_connection_id]
        archive_connection.manage_open_connection()
        # the deferred one
        self.archive_deferred_connection_id = 'erp5_sql_connection4'
        addSQLConnection(self.archive_deferred_connection_id, '', db2)
        archive_deferred_connection = portal[
            self.archive_deferred_connection_id]
        archive_deferred_connection.manage_open_connection()

        # Create new catalog for destination
        self.original_catalog_id = 'erp5_mysql_innodb'
        self.new_catalog_id = self.original_catalog_id + '_2'
        cp_data = portal_catalog.manage_copyObjects(
            ids=('erp5_mysql_innodb', ))
        new_id = portal_catalog.manage_pasteObjects(cp_data)[0]['new_id']
        new_catalog_id = 'erp5_mysql_innodb_2'
        portal_catalog.manage_renameObject(id=new_id, new_id=new_catalog_id)

        # Create new catalog for archive
        self.archive_catalog_id = self.original_catalog_id + '_archive'
        cp_data = portal_catalog.manage_copyObjects(
            ids=('erp5_mysql_innodb', ))
        archive_id = portal_catalog.manage_pasteObjects(cp_data)[0]['new_id']
        archive_catalog_id = 'erp5_mysql_innodb_archive'
        portal_catalog.manage_renameObject(id=archive_id,
                                           new_id=archive_catalog_id)

        # Create an archive
        archive = portal_archive.newContent(
            portal_type="Archive",
            catalog_id=self.archive_catalog_id,
            connection_id=self.archive_connection_id,
            deferred_connection_id=self.archive_deferred_connection_id,
            priority=3,
            inventory_method_id='Archive_createAllInventory',
            test_method_id='Archive_test',
            stop_date_range_min=DateTime("2006/06/01"),
            stop_date_range_max=DateTime("2006/07/01"),
        )
        archive.ready()
        # Create an archive for destination catalog
        dest = portal_archive.newContent(
            portal_type="Archive",
            catalog_id=self.new_catalog_id,
            connection_id=self.new_connection_id,
            deferred_connection_id=self.new_deferred_connection_id,
            priority=1,
            test_method_id='Archive_test',
            stop_date_range_min=DateTime("2006/07/01"),
        )
        dest.ready()

        # make sure to commit to release any lock on tables
        self.commit()

        # Do archive
        portal_archive.manage_archive(destination_archive_id=dest.getId(),
                                      archive_id=archive.getId(),
                                      update_destination_sql_catalog=True,
                                      update_archive_sql_catalog=True,
                                      clear_destination_sql_catalog=True,
                                      clear_archive_sql_catalog=True)

        self.tic()
        self.assertEqual(portal_catalog.getSQLCatalog().id,
                         self.new_catalog_id)
        self.assertEqual(archive.getValidationState(), 'validated')
        self.assertEqual(dest.getValidationState(), 'validated')
        # Check objects organisation are indexed
        # in both archive and current catalog and old one
        path_list = [self.organisation.getRelativeUrl()]
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.original_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.archive_connection_id)
        # Create a new organisation and check it goes in both catalog and not old one
        self.organisation_1 = module.newContent(portal_type='Organisation',
                                                title="GreatTitle3")
        self.tic()
        path_list = [self.organisation_1.getRelativeUrl()]
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.original_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.archive_connection_id)

        # Check objects movement are indexed
        # in archive and old one and not in current catalog
        path_list = [self.mvt.getRelativeUrl()]
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.original_connection_id)
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.archive_connection_id)

        # Check inventory are indexed
        # in archive and old one and not in current catalog
        path_list = [self.inventory.getRelativeUrl()]
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.original_connection_id)
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.archive_connection_id)

        # Create a new movement and check it goes only in new catalog
        self.assertEqual(
            len(self.folder.searchFolder(portal_type="Dummy Movement")), 0)
        self.assertEqual(100, getInventory(node_uid=self.node.getUid()))
        self.new_mvt = self._makeMovement(
            quantity=50,
            stop_date=DateTime("2006/08/06"),
            simulation_state='delivered',
        )
        self.tic()
        self.assertEqual(
            len(self.folder.searchFolder(portal_type="Dummy Movement")), 1)
        # Check objects movement are indexed
        # not in archive and old one but in current catalog
        path_list = [self.new_mvt.getRelativeUrl()]
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.original_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.archive_connection_id)
        self.assertEqual(150, getInventory(node_uid=self.node.getUid()))

        # now play with preference to select to view document from archive
        portal_preferences = self.getPreferenceTool()
        self.pref = portal_preferences.newContent(
            id='user_pref',
            portal_type='Preference',
            preferred_archive=archive.getRelativeUrl())
        self.tic()
        self.getPreferenceTool().recursiveReindexObject()

        self.portal.portal_workflow.doActionFor(self.pref,
                                                'enable_action',
                                                wf_id='preference_workflow')
        self.assertEqual(self.pref.getPreferenceState(), 'enabled')

        path_list = [self.pref.getRelativeUrl()]
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.original_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.archive_connection_id)

        self.assertEqual(portal_catalog.getPreferredSQLCatalogId(),
                         archive.getCatalogId())
        self.assertEqual(
            len(self.folder.searchFolder(portal_type="Dummy Movement")), 1)

        # As we only have first movement in archive, inventory must be 100
        self.assertEqual(100, getInventory(node=self.node.getRelativeUrl()))

        # go on current catalog
        self.pref.edit(preferred_archive=None)
        self.tic()

        # unindex and reindex an older movement and check it's well reindexed
        self.inventory.unindexObject()
        self.tic()
        path_list = [self.inventory.getRelativeUrl()]
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.archive_connection_id)
        self.inventory.reindexObject()
        self.tic()
        path_list = [self.inventory.getRelativeUrl()]
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlInSQLPathList(
            path_list, connection_id=self.archive_connection_id)
        # check inventory in archive now
        self.pref.edit(preferred_archive=archive.getRelativeUrl())
        self.tic()
        self.assertEqual(100, getInventory(node=self.node.getRelativeUrl()))

        # check if we unindex an object, it's remove in all catalog:
        module.manage_delObjects([
            self.organisation_1.id,
        ])
        self.tic()
        path_list = [self.organisation_1.getRelativeUrl()]
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.new_connection_id)
        self.checkRelativeUrlNotInSQLPathList(
            path_list, connection_id=self.archive_connection_id)

        # check the current archive
        self.assertEqual(portal_archive.getCurrentArchive(), dest)
Example #34
0
 def startZServer(self, verbose=False):
     """Start HTTP ZServer in background"""
     utils = ZopeTestCase.utils
     if utils._Z2HOST is None:
         from Products.ERP5Type.tests.runUnitTest import tests_home
         log = os.path.join(tests_home, "Z2.log")
         message = "Running %s server at %s:%s\n"
         if int(os.environ.get('erp5_wsgi', 0)):
             from Products.ERP5.bin.zopewsgi import app_wrapper, createServer
             sockets = []
             server_type = 'HTTP'
             zserver = os.environ.get('zserver')
             try:
                 for ip, port in parseListeningAddress(zserver):
                     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                     try:
                         s.setsockopt(socket.SOL_SOCKET,
                                      socket.SO_REUSEADDR, 1)
                         s.bind((ip, port))
                         s.listen(0)
                     except socket.error as e:
                         s.close()
                         if e[0] != errno.EADDRINUSE:
                             raise
                         if zserver:
                             raise RuntimeError(str(e))
                     else:
                         if sockets:
                             webdav_ports = port,
                         else:
                             webdav_ports = ()
                         sockets.append(s)
                         if verbose:
                             ZopeTestCase._print(message %
                                                 (server_type, ip, port))
                         if webdav_ports:
                             break
                         server_type = 'WebDAV'
             except RuntimeError as e:
                 ZopeTestCase._print('Could not start %s server: %s\n' %
                                     (server_type, e))
             if sockets:
                 logger = logging.getLogger("access")
                 logger.addHandler(logging.FileHandler(log))
                 logger.propagate = False
                 hs = createServer(app_wrapper(webdav_ports=webdav_ports),
                                   logger,
                                   sockets=sockets)
                 utils._Z2HOST, utils._Z2PORT = hs.addr
                 t = Thread(target=hs.run)
                 t.setDaemon(1)
                 t.start()
         else:
             _print = lambda hs: verbose and ZopeTestCase._print(message % (
                 hs.server_protocol, hs.server_name, hs.server_port))
             try:
                 hs = createZServer(log)
             except RuntimeError as e:
                 ZopeTestCase._print(str(e))
             else:
                 utils._Z2HOST, utils._Z2PORT = hs.server_name, hs.server_port
                 _print(hs)
                 try:
                     _print(createZServer(log, zserver_type='webdav'))
                 except RuntimeError as e:
                     ZopeTestCase._print(
                         'Could not start webdav zserver: %s\n' % e)
                 t = Thread(target=Lifetime.loop)
                 t.setDaemon(1)
                 t.start()
         from Products.CMFActivity import ActivityTool
         # Reset, in case that getServerAddress was already called,
         # in which case, the value was ('', '')
         if ActivityTool._server_address:
             if ActivityTool.currentNode == ActivityTool._server_address:
                 ActivityTool.currentNode = None
             ActivityTool._server_address = None
     return utils._Z2HOST, utils._Z2PORT
Example #35
0
    def test_03_LatestContent(self, quiet=quiet, run=run_all_test):
        """ Test latest content for a Web Section. Test different use case like languaeg, workflow state.
   """
        if not run: return
        if not quiet:
            message = '\ntest_03_LatestContent'
            ZopeTestCase._print(message)
        portal = self.getPortal()
        self.setupWebSite()
        websection = self.setupWebSection()
        portal_categories = portal.portal_categories
        publication_section_category_id_list = [
            'documentation', 'administration'
        ]
        for category_id in publication_section_category_id_list:
            portal_categories.publication_section.newContent(
                portal_type='Category', id=category_id)
        #set predicate on web section using 'publication_section'
        websection.edit(
            membership_criterion_base_category=['publication_section'],
            membership_criterion_category=[
                'publication_section/%s' %
                publication_section_category_id_list[0]
            ])
        self.tic()

        self.assertEqual(0, len(websection.getDocumentValueList()))
        # create pages belonging to this publication_section 'documentation'
        web_page_en = portal.web_page_module.newContent(
            portal_type='Web Page',
            language='en',
            publication_section_list=publication_section_category_id_list[:1])
        web_page_en.publish()
        self.tic()
        self.assertEqual(1,
                         len(websection.getDocumentValueList(language='en')))
        self.assertEqual(
            web_page_en,
            websection.getDocumentValueList(language='en')[0].getObject())

        # create pages belonging to this publication_section 'documentation' but for 'bg' language
        web_page_bg = portal.web_page_module.newContent(
            portal_type='Web Page',
            language='bg',
            publication_section_list=publication_section_category_id_list[:1])
        web_page_bg.publish()
        self.tic()
        self.assertEqual(1,
                         len(websection.getDocumentValueList(language='bg')))
        self.assertEqual(
            web_page_bg,
            websection.getDocumentValueList(language='bg')[0].getObject())

        # reject page
        web_page_bg.reject()
        self.tic()
        self.assertEqual(0,
                         len(websection.getDocumentValueList(language='bg')))

        # publish page and search without a language (by default system should return 'en' docs only)
        web_page_bg.publish()
        self.tic()
        self.assertEqual(1, len(websection.getDocumentValueList()))
        self.assertEqual(web_page_en,
                         websection.getDocumentValueList()[0].getObject())
Example #36
0
    def test_04_WebSectionAuthorizationForcedForDefaultDocument(
            self, quiet=quiet, run=run_all_test):
        """ Check that when a Web Section contains a default document not accessible by user we have a chance to
        require user to login.
        Whether or not an user will login is controlled by a property on Web Section (authorization_forced).
    """
        if not run: return
        if not quiet:
            message = '\ntest_04_WebSectionAuthorizationForcedForDefaultDocument'
            ZopeTestCase._print(message)
        self.setupWebSite()
        websection = self.setupWebSection()
        web_page_reference = 'default-document-reference'
        web_page_en = self.portal.web_page_module.newContent(
            portal_type='Web Page',
            language='en',
            reference=web_page_reference)
        # this way it's not viewable by anonymous and we can test
        web_page_en.releaseAlive()
        websection.setAggregateValue(web_page_en)
        websection.setAuthorizationForced(1)
        self.tic()

        # make sure that getDefaultDocumentValue() will return the same document for logged in user
        # if default document is accessible
        self.assertEqual(web_page_en.getUid(),
                         websection.getDefaultDocumentValue().getUid())

        # check Unauthorized exception is raised for anonymous when authorization_forced is set
        self.logout()
        self.assertEqual(None, websection.getDefaultDocumentValue())
        self.assertRaises(Unauthorized, websection)

        # Anonymous User should not get Unauthorized when authorization_forced is not set
        self.login()
        websection.setAuthorizationForced(0)
        self.tic()

        self.logout()
        self.assertEqual(None, websection.getDefaultDocumentValue())
        try:
            websection()
        except Unauthorized:
            self.fail("Web Section should not prompt user for login.")

        self.login()
        web_page_list = []
        for iteration in range(0, 10):
            web_page = self.getPortal().web_page_module.newContent(
                portal_type='Web Page',
                reference="%s_%s" % (web_page_reference, iteration),
                language='en',
            )
            web_page.publish()
            self.tic()
            self.commit()
            web_page_list.append(web_page)
        websection.setAggregateValueList(web_page_list)
        self.tic()
        self.commit()
        self.assertEqual(5, len(websection.getDocumentValueList(limit=5)))