testERP5Web.py 44.7 KB
Newer Older
1
##############################################################################
2
# -*- coding: utf-8 -*-
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 29 30 31
#
# Copyright (c) 2004, 2005, 2006 Nexedi SARL and Contributors. 
# All Rights Reserved.
#          Romain Courteaud <romain@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.
#
##############################################################################

import os
32
import re
33
import unittest
34
import random
35

36
from AccessControl import Unauthorized
37
from AccessControl.SecurityManagement import newSecurityManager
38
from AccessControl.SecurityManagement import getSecurityManager
39 40
from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
41
from Products.ERP5Type.tests.utils import DummyLocalizer
42
from Products.ERP5Type.tests.utils import createZODBPythonScript
43

44
LANGUAGE_LIST = ('en', 'fr', 'de', 'bg',)
45 46 47 48

class TestERP5Web(ERP5TypeTestCase, ZopeTestCase.Functional):
  """Test for erp5_web business template.
  """
49
  run_all_test = 1
50
  quiet = 0
51 52
  manager_username = 'zope'
  manager_password = 'zope'
53
  website_id = 'test'
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68


  def getTitle(self):
    return "ERP5Web"

  def login(self, quiet=0, run=run_all_test):
    uf = self.getPortal().acl_users
    uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
    user = uf.getUserById(self.manager_username).__of__(uf)
    newSecurityManager(None, user)

  def getBusinessTemplateList(self):
    """
    Return the list of required business templates.
    """
69 70 71
    return ('erp5_base',
            'erp5_web',
            )
72 73 74

  def afterSetUp(self):
    self.login()
75
    portal = self.getPortal()
76
    self.web_page_module = self.portal.web_page_module
77
    self.web_site_module = self.portal.web_site_module
78
    portal.Localizer.manage_changeDefaultLang(language = 'en')
79 80
    self.portal_id = self.portal.getId()

81 82 83 84 85
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
    get_transaction().commit()
    self.tic()

86
  def beforeTearDown(self):
87 88 89
#    get_transaction().abort()
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
90

91
  def setupWebSite(self, **kw):
92
    """
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
      Setup Web Site
    """
    portal = self.getPortal()
    request = self.app.REQUEST
    
    # add supported languages for Localizer
    localizer = portal.Localizer
    for language in LANGUAGE_LIST:
      localizer.manage_addLanguage(language = language)
      
    # create website
    if hasattr(self.web_site_module, self.website_id):
      self.web_site_module.manage_delObjects(self.website_id)
    website = self.getPortal().web_site_module.newContent(portal_type = 'Web Site', 
                                                          id = self.website_id,
                                                          **kw)
    get_transaction().commit()
    self.tic()
    return website
    
  def setupWebSection(self, **kw):
114
    """
115 116 117 118
      Setup Web Section
    """
    web_site_module = self.portal.getDefaultModule('Web Site')
    website = web_site_module[self.website_id]
119
    websection = website.newContent(portal_type='Web Section', **kw)
120 121
    self.websection = websection
    kw = dict(criterion_property_list = 'portal_type',
122 123
              membership_criterion_base_category_list='',
              membership_criterion_category_list='')
124
    websection.edit(**kw)
125 126 127 128
    websection.setCriterion(property='portal_type',
                            identity=['Web Page'],
                            max='', 
                            min='')
129 130 131 132 133 134
                            
    get_transaction().commit()
    self.tic()
    return websection
   

135 136
  def setupWebSitePages(self, prefix, suffix=None, version='0.1', 
                        language_list=LANGUAGE_LIST, **kw):
137 138 139 140 141 142 143 144 145 146 147 148
    """
      Setup some Web Pages.
    """
    webpage_list = []
    portal = self.getPortal()
    request = self.app.REQUEST
    web_site_module = self.portal.getDefaultModule('Web Site')
    website = web_site_module[self.website_id]
    
    # create sample web pages
    for language in language_list:
      if suffix is not None:
149
        reference = '%s-%s' % (prefix, language)
150 151
      else:
        reference = prefix
152 153 154 155 156
      webpage = self.web_page_module.newContent(portal_type='Web Page', 
                                                reference=reference,
                                                version=version,
                                                language=language,
                                                **kw)
157
      webpage.publish()
158 159
      get_transaction().commit()
      self.tic()
160 161 162 163 164 165 166 167 168 169 170 171
      self.assertEquals(language, webpage.getLanguage())
      self.assertEquals(reference, webpage.getReference())
      self.assertEquals(version, webpage.getVersion())
      self.assertEquals('published', webpage.getValidationState())
      webpage_list.append(webpage)
    
    return webpage_list
    
  def test_01_WebSiteRecatalog(self, quiet=quiet, run=run_all_test):
    """
      Test that a recataloging works for Web Site documents
    """
172
    if not run: return
173 174 175 176 177
    if not quiet:
      message = '\ntest_01_WebSiteRecatalog'
      ZopeTestCase._print(message)
    
    self.setupWebSite()
178
    portal = self.getPortal()
179
    web_site_module = self.portal.getDefaultModule('Web Site')
180 181
    web_site = web_site_module[self.website_id]

182 183 184 185 186 187 188 189
    self.assertTrue(web_site is not None)
    # Recatalog the Web Site document
    portal_catalog = self.getCatalogTool()
    try:
      portal_catalog.catalog_object(web_site)
    except:
      self.fail('Cataloging of the Web Site failed.')

190

191
  def test_02_EditSimpleWebPage(self, quiet=quiet, run=run_all_test):
192 193
    """
      Simple Case of creating a web page.
194
    """
195
    if not run: return
196 197 198
    if not quiet:
      message = '\ntest_02_EditSimpleWebPage'
      ZopeTestCase._print(message)
199 200 201 202
    page = self.web_page_module.newContent(portal_type='Web Page')
    page.edit(text_content='<b>OK</b>')
    self.assertEquals('text/html', page.getTextFormat())
    self.assertEquals('<b>OK</b>', page.getTextContent())
203
    
204
  def test_03_CreateWebSiteUser(self, quiet=quiet, run=run_all_test):
205 206 207
    """
      Create Web site User.
    """
208
    if not run: return
209 210 211 212
    if not quiet:
      message = '\ntest_03_CreateWebSiteUser'
      ZopeTestCase._print(message)
    self.setupWebSite()
213 214 215 216 217 218 219 220 221 222 223
    portal = self.getPortal()
    request = self.app.REQUEST
    kw = dict(reference = 'web',
              first_name = 'TestFN',
              last_name = 'TestLN',
              default_email_text = 'test@test.com',
              password = 'abc',
              password_confirm = 'abc',)
    for key, item in kw.items():
      request.set('field_your_%s' %key, item)
    website = portal.web_site_module[self.website_id]
224
    website.WebSite_createWebSiteAccount('WebSite_viewRegistrationDialog')
225
    
226 227 228
    get_transaction().commit()
    self.tic()
    
229 230 231 232 233 234 235 236 237 238 239 240 241
    # find person object by reference
    person = website.ERP5Site_getAuthenticatedMemberPersonValue(kw['reference'])
    self.assertEquals(person.getReference(), kw['reference'])
    self.assertEquals(person.getFirstName(), kw['first_name'])
    self.assertEquals(person.getLastName(), kw['last_name'])
    self.assertEquals(person.getDefaultEmailText(), kw['default_email_text'])
    self.assertEquals(person.getValidationState(), 'validated')

    # check if user account is 'loggable' 
    uf = portal.acl_users
    user = uf.getUserById( kw['reference'])
    self.assertEquals(str(user),  kw['reference'])
    self.assertEquals(1, user.has_role(('Member', 'Authenticated',)))
242 243 244 245 246 247
    
  def test_04_WebPageTranslation(self, quiet=quiet, run=run_all_test):
    """
      Simple Case of showing the proper Web Page based on 
      current user selected language in browser.
    """
248
    if not run: return
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    if not quiet:
      message = '\ntest_04_WebPageTranslation'
      ZopeTestCase._print(message)
    portal = self.getPortal()
    request = self.app.REQUEST
    website = self.setupWebSite()
    websection = self.setupWebSection()
    page_reference = 'default-webpage'
    webpage_list  = self.setupWebSitePages(prefix = page_reference)
   
    # set default web page for section
    found_by_reference = portal.portal_catalog(name = page_reference,
                                               portal_type = 'Web Page')
    found =  found_by_reference[0].getObject()
    websection.edit(categories_list = ['aggregate/%s' %found.getRelativeUrl(),])
    self.assertEqual([found.getReference(),],
                      websection.getAggregateReferenceList())
    # even though we create many pages we should get only one
    # this is the most recent one since all share the same reference
    self.assertEquals(1, len(websection.WebSection_getDocumentValueList()))
     
    # use already created few pages in different languages with same reference
    # and check that we always get the right one based on selected 
    # by us language
    for language in LANGUAGE_LIST:
      # set default language in Localizer only to check that we get
      # the corresponding web page for language. 
      # XXX: Extend API so we can select language from REQUEST
      portal.Localizer.manage_changeDefaultLang(language = language)
      default_document = websection.getDefaultDocumentValue()
      self.assertEquals(language, default_document.getLanguage())
280
    
281
  def test_05_WebPageTextContentSubstitutions(self, quiet=quiet, run=run_all_test):
282 283 284 285
    """
      Simple Case of showing the proper text content with and without a substitution
      mapping method.
    """
286
    if not run: return
287
    if not quiet:
288
      message = '\ntest_05_WebPageTextContentSubstituions'
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
      ZopeTestCase._print(message)

    content = '<a href="${toto}">$titi</a>'
    substituted_content = '<a href="foo">bar</a>'
    mapping = dict(toto='foo', titi='bar')

    portal = self.getPortal()
    document = portal.web_page_module.newContent(portal_type='Web Page', 
            text_content=content)
   
    # No substitution should occur.
    self.assertEquals(document.asStrippedHTML(), content)

    klass = document.__class__
    klass.getTestSubstitutionMapping = lambda self, **kw: mapping
    document.setTextContentSubstitutionMappingMethodId('getTestSubstitutionMapping')

    # Substitutions should occur.
    self.assertEquals(document.asStrippedHTML(), substituted_content)

    klass._getTestSubstitutionMapping = klass.getTestSubstitutionMapping
    document.setTextContentSubstitutionMappingMethodId('_getTestSubstitutionMapping')

    # Even with the same callable object, a restricted method id should not be callable.
    self.assertRaises(Unauthorized, document.asStrippedHTML)

315
  def test_06_DefaultDocumentForWebSection(self, quiet=quiet, run=run_all_test):
316 317 318 319 320 321 322 323 324 325
    """
      Testing the default document for a Web Section.

      If a Web Section has a default document defined and if that default
      document is published, then getDefaultDocumentValue on that 
      web section should return the latest version in the most 
      appropriate language of that default document.
        
      Note: due to generic ERP5 Web implementation this test highly depends 
      on WebSection_geDefaulttDocumentValueList
Ivan Tyagov's avatar
Ivan Tyagov committed
326 327 328
    """
    if not run: return
    if not quiet:
329
      message = '\ntest_06_DefaultDocumentForWebSection'
Ivan Tyagov's avatar
Ivan Tyagov committed
330 331 332 333 334 335 336 337
      ZopeTestCase._print(message)    
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    publication_section_category_id_list = ['documentation',  'administration']
    
    # create pages belonging to this publication_section 'documentation'
    web_page_en = portal.web_page_module.newContent(portal_type = 'Web Page', 
338
                                                 id='section_home',
Ivan Tyagov's avatar
Ivan Tyagov committed
339 340 341 342 343 344
                                                 language = 'en', 
                                                 reference='NXD-DDP', 
                                                 publication_section_list=publication_section_category_id_list[:1])    
    websection.setAggregateValue(web_page_en)
    get_transaction().commit()
    self.tic()
345
    self.assertEqual(None, websection.getDefaultDocumentValue())
Ivan Tyagov's avatar
Ivan Tyagov committed
346 347 348 349
    # publish it
    web_page_en.publish()
    get_transaction().commit()
    self.tic()
350 351 352 353 354 355 356 357
    self.assertEqual(web_page_en, websection.getDefaultDocumentValue())
    # and make sure that the base meta tag which is generated
    # uses the web section rather than the portal
    html_page = websection()
    from Products.ERP5.Document.Document import Document
    base_list = re.findall(Document.base_parser, str(html_page))
    base_url = base_list[0]
    self.assertEqual(base_url, "%s/%s/" % (websection.absolute_url(), websection.getId()))
358
    
359
  def test_06b_DefaultDocumentForWebSite(self, quiet=quiet, run=run_all_test):
360 361 362 363 364 365 366 367 368 369 370 371 372
    """
      Testing the default document for a Web Site.

      If a Web Section has a default document defined and if that default
      document is published, then getDefaultDocumentValue on that 
      web section should return the latest version in the most 
      appropriate language of that default document.
        
      Note: due to generic ERP5 Web implementation this test highly depends 
      on WebSection_geDefaulttDocumentValueList
    """
    if not run: return
    if not quiet:
373
      message = '\ntest_06b_DefaultDocumentForWebSite'
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
      ZopeTestCase._print(message)    
    portal = self.getPortal()
    website = self.setupWebSite()
    publication_section_category_id_list = ['documentation',  'administration']
    
    # create pages belonging to this publication_section 'documentation'
    web_page_en = portal.web_page_module.newContent(portal_type = 'Web Page', 
                                                 id='site_home',
                                                 language = 'en', 
                                                 reference='NXD-DDP-Site', 
                                                 publication_section_list=publication_section_category_id_list[:1])    
    website.setAggregateValue(web_page_en)
    get_transaction().commit()
    self.tic()
    self.assertEqual(None, website.getDefaultDocumentValue())
    # publish it
    web_page_en.publish()
    get_transaction().commit()
    self.tic()
    self.assertEqual(web_page_en, website.getDefaultDocumentValue())
    # and make sure that the base meta tag which is generated
    # uses the web site rather than the portal
    html_page = website()
    from Products.ERP5.Document.Document import Document
    base_list = re.findall(Document.base_parser, str(html_page))
    base_url = base_list[0]
    self.assertEqual(base_url, "%s/%s/" % (website.absolute_url(), website.getId()))

402
  def test_07_WebSection_getDocumentValueList(self, quiet=quiet, run=run_all_test):
403 404
    """ Check getting getDocumentValueList from Web Section.
    """
405
    if not run: return
406
    if not quiet:
407
      message = '\ntest_07_WebSection_getDocumentValueList'
408
      ZopeTestCase._print(message)
409 410 411 412
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    publication_section_category_id_list = ['documentation',  'administration']
413

414
    #set predicate on web section using 'publication_section'
415
    websection.edit(membership_criterion_base_category = ['publication_section'],
416 417
                     membership_criterion_category=['publication_section/%s' \
                                                    % publication_section_category_id_list[0]])
418 419 420
    # clean up
    self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
    portal.portal_categories.publication_section.manage_delObjects(
421
                                      list(portal.portal_categories.publication_section.objectIds()))
422 423
    # create categories
    for category_id in publication_section_category_id_list:
424
      portal.portal_categories.publication_section.newContent(portal_type = 'Category',
425 426
                                                              id = category_id)

427 428 429 430 431 432 433 434 435 436 437 438 439 440
    web_page_list = []
    property_dict = { '01' : dict(language = 'en' , version = "1" , reference = "A"),
                      '02' : dict(language = 'en' , version = "2" , reference = "B"),
                      '03' : dict(language = 'en' , version = "3" , reference = "C"),
                      '04' : dict(language = 'pt' , version = "1" , reference = "A"),
                      '05' : dict(language = 'pt' , version = "2" , reference = "C"),
                      '06' : dict(language = 'pt' , version = "3" , reference = "B"),
                      '07' : dict(language = 'ja' , version = "1" , reference = "C"),
                      '08' : dict(language = 'ja' , version = "2" , reference = "A"),
                      '09' : dict(language = 'ja' , version = "3" , reference = "B"),
                      '10' : dict(language = 'en' , version = "2" , reference = "D"),
                      '11' : dict(language = 'ja' , version = "3" , reference = "E"),
                      '12' : dict(language = 'pt' , version = "3" , reference = "F"),
                      '13' : dict(language = 'en' , version = "3" , reference = "D"),
441 442
                      '14' : dict(language = 'ja' , version = "2" , reference = "E"),
                      '15' : dict(language = 'pt' , version = "2" , reference = "F"),
443 444
                    }
    sequence_one = property_dict.keys()
445 446 447 448
    sequence_two = ['01', '13', '12', '09', '06', '15' , '04', '11', '02', '05', '03',
                    '07', '10', '08', '14' ]
    sequence_three = ['05', '12', '13', '14',  '06', '09', '10', '07', '03', '01', '02',
                    '11', '04', '08' , '15']
449 450
    
    sequence_count = 0
451
    for sequence in [ sequence_one , sequence_two , sequence_three ]:
452 453
      sequence_count += 1
      if not quiet:
454
        message = '\ntest_07_WebSection_getDocumentValueList (Sequence %s)' \
455 456 457
                                                                % (sequence_count)
        ZopeTestCase._print(message)

458 459
      for key in sequence:
        web_page = self.portal.web_page_module.newContent(
460
                                  title=key,
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
                                  portal_type = 'Web Page',
                                  publication_section_list=publication_section_category_id_list[:1])
  
        web_page.edit(**property_dict[key])
        get_transaction().commit()
        self.tic()
        web_page_list.append(web_page)
  
      get_transaction().commit()
      self.tic()
      # in draft state no documents should belong to this Web Section
      self.assertEqual(0, len(websection.getDocumentValueList()))
  
      # when published all web pages should belong to it
      for web_page in web_page_list:
        web_page.publish()
      get_transaction().commit()
      self.tic()
479

480
      # Test for limit parameter
481
      self.assertEqual(2, len(websection.getDocumentValueList(limit=2)))
482 483

      # Testing for language parameter
484 485 486 487 488
      self.assertEqual(4, len(websection.getDocumentValueList()))
      self.assertEqual(['en' , 'en', 'en', 'en'], 
                       [ w.getLanguage()  for w in websection.getDocumentValueList()])
  
      pt_document_value_list = websection.getDocumentValueList(language='pt')
489
      self.assertEqual(4, len(pt_document_value_list))
490 491 492 493
      self.assertEqual(['pt' , 'pt', 'pt', 'pt'],
                           [ w.getObject().getLanguage() for w in pt_document_value_list])
  
      ja_document_value_list = websection.getDocumentValueList(language='ja')
494
      self.assertEqual(4, len(ja_document_value_list))
495 496
      self.assertEqual(['ja' , 'ja', 'ja', 'ja'],
                           [ w.getLanguage() for w in ja_document_value_list])
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

      # Testing for all_versions parameter
      en_document_value_list = websection.getDocumentValueList(all_versions=1)
      self.assertEqual(5, len(en_document_value_list))
      self.assertEqual(['en' , 'en', 'en', 'en', 'en'],
                       [ w.getLanguage()  for w in en_document_value_list])

      pt_document_value_list = websection.getDocumentValueList(language='pt',
                                                               all_versions=1)
      self.assertEqual(5, len(pt_document_value_list))
      self.assertEqual(['pt' , 'pt', 'pt', 'pt', 'pt'],
                           [ w.getObject().getLanguage() for w in pt_document_value_list])

      ja_document_value_list = websection.getDocumentValueList(language='ja', 
                                                               all_versions=1)
      self.assertEqual(5, len(ja_document_value_list))
      self.assertEqual(['ja' , 'ja', 'ja', 'ja', 'ja'],
                           [ w.getLanguage() for w in ja_document_value_list])

      # Tests for all_languages parameter
517 518 519 520 521 522 523 524 525 526 527 528
      en_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1)
      self.assertEqual(6, len(en_document_value_list))
      self.assertEqual(4, len([ w.getLanguage() for w in en_document_value_list \
                              if w.getLanguage() == 'en']))
      self.assertEqual(1, len([ w.getLanguage() for w in en_document_value_list \
                              if w.getLanguage() == 'pt']))
      self.assertEqual(['3'], [ w.getVersion() for w in en_document_value_list \
                              if w.getLanguage() == 'pt'])
      self.assertEqual(1, len([ w.getLanguage() for w in en_document_value_list \
                              if w.getLanguage() == 'ja']))
      self.assertEqual(['3'], [ w.getVersion() for w in en_document_value_list \
                              if w.getLanguage() == 'ja'])
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
      pt_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              language='pt')
      self.assertEqual(6, len(pt_document_value_list))
      self.assertEqual(4, len([ w.getLanguage() for w in pt_document_value_list \
                              if w.getLanguage() == 'pt']))
      self.assertEqual(1, len([ w.getLanguage() for w in pt_document_value_list \
                              if w.getLanguage() == 'en']))
      self.assertEqual(['3'], [ w.getVersion() for w in pt_document_value_list \
                              if w.getLanguage() == 'en'])
      self.assertEqual(1, len([ w.getLanguage() for w in pt_document_value_list \
                              if w.getLanguage() == 'ja']))
      self.assertEqual(['3'], [ w.getVersion() for w in pt_document_value_list \
                              if w.getLanguage() == 'ja'])
  
      ja_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              language='ja')
      self.assertEqual(6, len(ja_document_value_list))
      self.assertEqual(4, len([ w.getLanguage() for w in ja_document_value_list \
                              if w.getLanguage() == 'ja']))
      self.assertEqual(1, len([ w.getLanguage() for w in ja_document_value_list \
                              if w.getLanguage() == 'pt']))
      self.assertEqual(['3'], [ w.getVersion() for w in ja_document_value_list \
                              if w.getLanguage() == 'pt'])
      self.assertEqual(1, len([ w.getLanguage() for w in ja_document_value_list \
                              if w.getLanguage() == 'en']))
      self.assertEqual(['3'], [ w.getVersion() for w in ja_document_value_list \
                            if w.getLanguage() == 'en'])

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
      # Tests for all_languages and all_versions 
      en_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              all_versions=1)

      pt_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              all_versions=1,
                                                                              language='pt')

      ja_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              all_versions=1,
                                                                              language='ja')

      for document_value_list in [ en_document_value_list, pt_document_value_list , 
                                   ja_document_value_list]:

        self.assertEqual(15, len(document_value_list))
        self.assertEqual(5, len([ w.getLanguage() for w in document_value_list \
                                if w.getLanguage() == 'en']))
        self.assertEqual(5, len([ w.getLanguage() for w in en_document_value_list \
                                if w.getLanguage() == 'pt']))
        self.assertEqual(5, len([ w.getLanguage() for w in en_document_value_list \
                                if w.getLanguage() == 'ja']))

      # Tests for sort_on parameter
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
      self.assertEqual(['A' , 'B', 'C', 'D'],
                       [ w.getReference()  for w in \
                         websection.getDocumentValueList(sort_on=[('reference', 'ASC')])])

      self.assertEqual(['01' , '02', '03', '13'],
                       [ w.getTitle()  for w in \
                         websection.getDocumentValueList(sort_on=[('title', 'ASC')])])

      self.assertEqual(['D' , 'C', 'B', 'A'],
                       [ w.getReference()  for w in \
                         websection.getDocumentValueList(sort_on=[('reference', 'DESC')])])


      self.assertEqual(['13' , '03', '02', '01'],
                       [ w.getTitle()  for w in \
                         websection.getDocumentValueList(sort_on=[('reference', 'DESC')])])

      self.assertEqual(['A' , 'B', 'C', 'D' , 'E' , 'F'],
                       [ w.getReference()  for w in \
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('reference', 'ASC')])])
     
      self.assertEqual(['01' , '02', '03', '11' , '12' , '13'],
                       [ w.getTitle()  for w in \
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('title', 'ASC')])])


      self.assertEqual(['F' , 'E', 'D', 'C' , 'B' , 'A'],
                       [ w.getReference()  for w in \
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('reference', 'DESC')])])

      self.assertEqual(['13' , '12', '11', '03' , '02' , '01'],
                       [ w.getTitle()  for w in \
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('title', 'DESC')])])

620
      self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
621

622
  def test_08_AcquisitionWrappers(self, quiet=quiet, run=run_all_test):
623 624 625 626 627 628
    """Test acquisition wrappers of documents.
    Check if documents obtained by getDefaultDocumentValue, getDocumentValue
    and getDocumentValueList are wrapped appropriately.
    """
    if not run: return
    if not quiet:
629
      message = '\ntest_08_AcquisitionWrappers'
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
      ZopeTestCase._print(message)    

    portal = self.getPortal()

    # Make its own publication section category.
    publication_section = portal.portal_categories['publication_section']
    if publication_section._getOb('my_test_category', None) is None:
      publication_section.newContent(portal_type='Category',
                                     id='my_test_category',
                                     title='Test')
      get_transaction().commit()
      self.tic()

    website = self.setupWebSite()
    websection = self.setupWebSection(
            membership_criterion_base_category_list=('publication_section',),
            membership_criterion_category=('publication_section/my_test_category',),
            )
    
    # Create at least two documents which belong to the publication section
    # category.
    web_page_list = self.setupWebSitePages('test1',
            language_list=('en',),
            publication_section_list=('my_test_category',))
    web_page_list2 = self.setupWebSitePages('test2',
            language_list=('en',),
            publication_section_list=('my_test_category',))

    # We need a default document.
    websection.setAggregateValue(web_page_list[0])
    get_transaction().commit()
    self.tic()
    
    # Obtain documens in various ways.
    default_document = websection.getDefaultDocumentValue()
    self.assertNotEquals(default_document, None)

    document1 = websection.getDocumentValue('test1')
    self.assertNotEquals(document1, None)
    document2 = websection.getDocumentValue('test2')
    self.assertNotEquals(document2, None)

    document_list = websection.getDocumentValueList()
    self.assertNotEquals(document_list, None)
    self.assertNotEquals(len(document_list), 0)

    # Check if they have good acquisition wrappers.
    for doc in (default_document, document1, document2) + tuple(document_list):
      self.assertEquals(doc.aq_parent, websection)
      self.assertEquals(doc.aq_parent.aq_parent, website)
680

681
  def test_09_WebSiteSkinSelection(self, quiet=quiet, run=run_all_test):
682 683 684 685 686
    """Test skin selection through a Web Site.
    Check if a Web Site can change a skin selection based on a property.
    """
    if not run: return
    if not quiet:
687
      message = '\ntest_09_WebSiteSkinSelection'
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
      ZopeTestCase._print(message)    

    portal = self.getPortal()
    ps = portal.portal_skins
    website = self.setupWebSite()

    # First, make sure that we use the default skin selection.
    portal.changeSkin(ps.getDefaultSkin())
    get_transaction().commit()
    self.tic()

    # Make some skin stuff.
    if ps._getOb('test_erp5_web', None) is not None:
      ps.manage_delObjects(['test_erp5_web'])

    addFolder = ps.manage_addProduct['OFSP'].manage_addFolder
    addFolder(id='test_erp5_web')

    if ps.getSkinPath('Test ERP5 Web') is not None:
      ps.manage_skinLayers(del_skin=1, chosen=('Test ERP5 Web',))
      
    path = ps.getSkinPath(ps.getDefaultSkin())
    self.assertNotEquals(path, None)
    ps.manage_skinLayers(add_skin=1, skinname='Test ERP5 Web',
            skinpath=['test_erp5_web'] + path.split(','))

    # Now we need skins which don't conflict with any other.
    createZODBPythonScript(ps.erp5_web,
            'WebSite_test_13_WebSiteSkinSelection',
            '', 'return "foo"')
    createZODBPythonScript(ps.test_erp5_web,
            'WebSite_test_13_WebSiteSkinSelection',
            '', 'return "bar"')

    get_transaction().commit()
    self.tic()

    path = website.absolute_url_path() + '/WebSite_test_13_WebSiteSkinSelection'
    request = portal.REQUEST

    # With the default skin.
    request['PARENTS'] = [self.app]
    self.assertEquals(request.traverse(path)(), 'foo')

    # With the test skin.
    website.setSkinSelectionName('Test ERP5 Web')
    get_transaction().commit()
    self.tic()

    request['PARENTS'] = [self.app]
    self.assertEquals(request.traverse(path)(), 'bar')

740
  def test_10_getDocumentValueList(self, quiet=quiet, run=run_all_test):
741
    """Make sure that getDocumentValueList works."""
742 743 744 745 746
    if not run: return
    if not quiet:
      message = '\ntest_10_getDocumentValueList'
      ZopeTestCase._print(message)
      
747 748 749 750 751 752
    self.setupWebSite()
    website = self.web_site_module[self.website_id]
    website.getDocumentValueList(
      portal_type='Document',
      sort_on=[('translated_portal_type', 'ascending')])

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
class TestERP5WebWithSimpleSecurity(ERP5TypeTestCase):
  """
  Test for erp5_web with simple security.
  """
  run_all_test = 1
  quiet = 0

  def getBusinessTemplateList(self):
    return ('erp5_base',
            'erp5_web',
            )

  def getTitle(self):
    return "Web"

  def createUser(self, name, role_list):
    user_folder = self.getPortal().acl_users
    user_folder._doAddUser(name, 'password', role_list, [])

  def changeUser(self, name):
    self.old_user = getSecurityManager().getUser()
    user_folder = self.getPortal().acl_users
    user = user_folder.getUserById(name).__of__(user_folder)
    newSecurityManager(None, user)

  def afterSetUp(self):
    self.portal.Localizer = DummyLocalizer()
    self.createUser('admin', ['Manager'])
    self.createUser('erp5user', ['Auditor', 'Author'])
782
    self.createUser('web_user', ['Assignor'])
783 784 785
    get_transaction().commit()
    self.tic()

786 787 788 789 790
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
    get_transaction().commit()
    self.tic()

791
  def beforeTearDown(self):
792 793
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
794
    
795
  def test_01_AccessWebPageByReference(self, quiet=quiet, run=run_all_test):
796 797 798 799 800
    if not run: return
    if not quiet:
      message = '\ntest_01_AccessWebPageByReference'
      ZopeTestCase._print(message)

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
    self.changeUser('admin')
    site = self.portal.web_site_module.newContent(portal_type='Web Site',
                                                  id='site')
    section = site.newContent(portal_type='Web Section', id='section')

    get_transaction().commit()
    self.tic()

    section.setCriterionProperty('portal_type')
    section.setCriterion('portal_type', max='', identity=['Web Page'], min='')

    get_transaction().commit()
    self.tic()

    self.changeUser('erp5user')
    page_en = self.portal.web_page_module.newContent(portal_type='Web Page')
    page_en.edit(reference='my-first-web-page',
                 language='en',
                 version='1',
                 text_format='text/plain',
                 text_content='Hello, World!')

    get_transaction().commit()
    self.tic()

    page_en.publish()

    get_transaction().commit()
    self.tic()

    page_ja = self.portal.web_page_module.newContent(portal_type='Web Page')
    page_ja.edit(reference='my-first-web-page',
                 language='ja',
                 version='1',
                 text_format='text/plain',
                 text_content='こんにちは、世界!')

    get_transaction().commit()
    self.tic()

    page_ja.publish()

    get_transaction().commit()
    self.tic()

    # By Anonymous
    self.logout()

    self.portal.Localizer.changeLanguage('en')

    target = self.portal.restrictedTraverse('web_site_module/site/section/my-first-web-page')
    self.assertEqual('Hello, World!', target.getTextContent())

    self.portal.Localizer.changeLanguage('ja')

    target = self.portal.restrictedTraverse('web_site_module/site/section/my-first-web-page')
    self.assertEqual('こんにちは、世界!', target.getTextContent())
858 859 860
    
  def test_02_LocalRolesFromRoleDefinition(self, quiet=quiet, run=run_all_test):
    """ Test setting local roles on Web Site/ Web Sectio using ERP5 Role Definition objects . """
861 862 863 864
    if not run: return
    if not quiet:
      message = '\ntest_02_LocalRolesFromRoleDefinition'
      ZopeTestCase._print(message)
865 866 867 868 869 870
    portal = self.portal
    person_reference = 'webuser'
    site = portal.web_site_module.newContent(portal_type='Web Site',
                                                  id='site')
    section = site.newContent(portal_type='Web Section', id='section')
    person = portal.person_module.newContent(portal_type = 'Person', 
871
                                             reference = person_reference)
872 873
    # add Role Definition for site and section
    site_role_definition = site.newContent(portal_type = 'Role Definition', 
874 875
                                           role_name = 'Assignee', 
                                           agent = person.getRelativeUrl())
876
    section_role_definition = section.newContent(portal_type = 'Role Definition', 
877 878
                                                 role_name = 'Associate', 
                                                 agent = person.getRelativeUrl())
879 880 881 882
    get_transaction().commit()
    self.tic()
    # check if Role Definition have create local roles
    self.assertSameSet(('Assignee',),  
883
                          site.get_local_roles_for_userid(person_reference))
884
    self.assertSameSet(('Associate',),  
885
                          section.get_local_roles_for_userid(person_reference))
886 887 888 889 890 891 892
                                 
    # delete Role Definition and check again (local roles must be gone too)
    site.manage_delObjects(site_role_definition.getId())
    section.manage_delObjects(section_role_definition.getId())
    get_transaction().commit()
    self.tic()
    self.assertSameSet((),  
893 894 895 896 897 898 899
                       site.get_local_roles_for_userid(person_reference))
    self.assertSameSet((),
                       section.get_local_roles_for_userid(person_reference))


  def test_03_WebSection_getDocumentValueListSecurity(self, quiet=quiet, run=run_all_test):
    """ Test WebSection_getDocumentValueList behaviour and security"""
900 901 902 903
    if not run: return
    if not quiet:
      message = '\ntest_03_WebSection_getDocumentValueListSecurity'
      ZopeTestCase._print(message)
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module
    site = web_site_module.newContent(portal_type='Web Site',
                                      id='site')

    section = site.newContent(portal_type='Web Section', 
                              id='section')

    get_transaction().commit()
    self.tic()

    section.setCriterionProperty('portal_type')
    section.setCriterion('portal_type', max='', 
                         identity=['Web Page'], min='')

    get_transaction().commit()
    self.tic()

    self.changeUser('erp5user')
    page_en_0 = self.portal.web_page_module.newContent(portal_type='Web Page')
    page_en_0.edit(reference='my-first-web-page',
                 language='en',
                 version='1',
                 text_format='text/plain',
                 text_content='Hello, World!')

    page_en_1 = self.portal.web_page_module.newContent(portal_type='Web Page')
    page_en_1.edit(reference='my-first-web-page',
                 language='en',
                 version='2',
                 text_format='text/plain',
                 text_content='Hello, World!')

    page_en_2 = self.portal.web_page_module.newContent(portal_type='Web Page')
    page_en_2.edit(reference='my-second-web-page',
                 language='en',
                 version='2',
                 text_format='text/plain',
                 text_content='Hello, World!')

    page_jp_0 = self.portal.web_page_module.newContent(portal_type='Web Page')
    page_jp_0.edit(reference='my-first-japonese-page',
                 language='jp',
                 version='1',
                 text_format='text/plain',
                 text_content='Hello, World!')



    get_transaction().commit()
    self.changeUser('erp5user')
    self.tic()
    self.portal.Localizer.changeLanguage('en')
957

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))    

    self.changeUser('erp5user')
    page_en_0.publish()
    get_transaction().commit()
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
    self.assertEquals(page_en_0.getUid(),
                      section.WebSection_getDocumentValueList()[0].getUid())

    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # By Anonymous
    self.logout()
    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
    self.assertEquals(page_en_0.getUid(), 
                      section.WebSection_getDocumentValueList()[0].getUid())
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # Second Object
    self.changeUser('erp5user')
    page_en_1.publish()
    get_transaction().commit()
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
    self.assertEquals(page_en_1.getUid(), 
                      section.WebSection_getDocumentValueList()[0].getUid())
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # By Anonymous
    self.logout()
    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
    self.assertEquals(page_en_1.getUid(), 
                      section.WebSection_getDocumentValueList()[0].getUid())

    # Trird Object
    self.changeUser('erp5user')
    page_en_2.publish()
    get_transaction().commit()
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(2, len(section.WebSection_getDocumentValueList()))
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # By Anonymous
    self.logout()
    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(2, len(section.WebSection_getDocumentValueList()))
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

1020
    # First Japanese Object
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    self.changeUser('erp5user')
    page_jp_0.publish()
    get_transaction().commit()
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(2, len(section.WebSection_getDocumentValueList()))
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))

    # By Anonymous
    self.logout()
    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(2, len(section.WebSection_getDocumentValueList()))
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
    self.assertEquals(page_jp_0.getUid(), 
                      section.WebSection_getDocumentValueList()[0].getUid())
1039

1040

1041 1042 1043 1044 1045 1046
  def test_04_ExpireUserAction(self, quiet=quiet, run=run_all_test):
    """ Test the expire user action"""
    if not run: return
    if not quiet:
      message = '\ntest_04_ExpireUserAction'
      ZopeTestCase._print(message)
1047

1048 1049
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module
1050 1051 1052 1053 1054 1055 1056 1057 1058
    site = web_site_module.newContent(portal_type='Web Site', id='site')

    # create websections in a site and in anothers web sections
    section_1 = site.newContent(portal_type='Web Section', id='section_1')
    section_2 = site.newContent(portal_type='Web Section', id='section_2')
    section_3 = site.newContent(portal_type='Web Section', id='section_3')
    section_4 = site.newContent(portal_type='Web Section', id='section_4')
    section_5 = section_3.newContent(portal_type='Web Section', id='section_5')
    section_6 = section_4.newContent(portal_type='Web Section', id='section_6')
1059 1060 1061
    get_transaction().commit()
    self.tic()

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    # test if a manager can expire them
    try:
      section_1.expire()
      section_5.expire()
    except Unauthorized:
      self.fail("Admin should be able to expire a Web Section.")
      
    # test if a user (ASSIGNOR) can expire them
    self.changeUser('web_user')
    try:
      section_2.expire()
      section_6.expire()
    except Unauthorized:
      self.fail("An user should be able to expire a Web Section.")
      
  def test_05_createWebSection(self, quiet=quiet, run=run_all_test):
    """ Test to create web sections with many users """
    if not run: return
    if not quiet:
      message = '\ntest_05_createWebSection'
      ZopeTestCase._print(message)
      
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module
    site = web_site_module.newContent(portal_type='Web Site', id='site')
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    # test for admin
    try:
      section_1 = site.newContent(portal_type='Web Section', id='section_1')
      section_2 = section_1.newContent(portal_type='Web Section', id='section_2')
    except Unauthorized:
      self.fail("Admin should be able to create a Web Section.")

    # test as a web user (assignor)
    self.changeUser('web_user')
    try:
      section_2 = site.newContent(portal_type='Web Section', id='section_2')
      section_3 = section_2.newContent(portal_type='Web Section', id='section_3')
      self.fail("A web user should not be able to create a Web Section.")
    except Unauthorized:
      pass
1103

1104 1105
      
    
1106 1107 1108
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Web))
1109
  suite.addTest(unittest.makeSuite(TestERP5WebWithSimpleSecurity))
1110
  return suite