testERP5Web.py 59.1 KB
Newer Older
1
##############################################################################
2
# -*- coding: utf-8 -*-
3
#
4
# Copyright (c) 2004, 2005, 2006 Nexedi SARL and Contributors.
5 6 7 8
# All Rights Reserved.
#          Romain Courteaud <romain@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
9
# programmers who take the whole responsibility of assessing all potential
10 11
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
12
# guarantees and support are strongly adviced to contract a Free Software
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# 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.
#
##############################################################################

31
import re
32
import unittest
33

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

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

class TestERP5Web(ERP5TypeTestCase, ZopeTestCase.Functional):
  """Test for erp5_web business template.
  """
48
  run_all_test = 1
49
  quiet = 0
50 51
  manager_username = 'zope'
  manager_password = 'zope'
52
  website_id = 'test'
53 54 55 56 57 58

  def getTitle(self):
    return "ERP5Web"

  def login(self, quiet=0, run=run_all_test):
    uf = self.getPortal().acl_users
59
    uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
60 61 62 63 64 65 66
    user = uf.getUserById(self.manager_username).__of__(uf)
    newSecurityManager(None, user)

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

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

79 80
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
81
    transaction.commit()
82 83
    self.tic()

84
  def beforeTearDown(self):
85 86
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
87
    self.clearModule(self.portal.person_module)
88

89
  def setupWebSite(self, **kw):
90
    """
91 92 93 94
      Setup Web Site
    """
    portal = self.getPortal()
    request = self.app.REQUEST
95

96 97 98 99
    # add supported languages for Localizer
    localizer = portal.Localizer
    for language in LANGUAGE_LIST:
      localizer.manage_addLanguage(language = language)
100

101 102 103
    # create website
    if hasattr(self.web_site_module, self.website_id):
      self.web_site_module.manage_delObjects(self.website_id)
104
    website = self.getPortal().web_site_module.newContent(portal_type = 'Web Site',
105 106
                                                          id = self.website_id,
                                                          **kw)
107
    transaction.commit()
108 109
    self.tic()
    return website
110

111
  def setupWebSection(self, **kw):
112
    """
113 114 115 116
      Setup Web Section
    """
    web_site_module = self.portal.getDefaultModule('Web Site')
    website = web_site_module[self.website_id]
117
    websection = website.newContent(portal_type='Web Section', **kw)
118 119
    self.websection = websection
    kw = dict(criterion_property_list = 'portal_type',
120 121
              membership_criterion_base_category_list='',
              membership_criterion_category_list='')
122
    websection.edit(**kw)
123 124
    websection.setCriterion(property='portal_type',
                            identity=['Web Page'],
125
                            max='',
126
                            min='')
127

128
    transaction.commit()
129 130 131
    self.tic()
    return websection

132
  def setupWebSitePages(self, prefix, suffix=None, version='0.1',
133
                        language_list=LANGUAGE_LIST, **kw):
134 135 136 137 138 139 140 141
    """
      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]
142

143 144 145
    # create sample web pages
    for language in language_list:
      if suffix is not None:
146
        reference = '%s-%s' % (prefix, language)
147 148
      else:
        reference = prefix
149
      webpage = self.web_page_module.newContent(portal_type='Web Page',
150 151 152 153
                                                reference=reference,
                                                version=version,
                                                language=language,
                                                **kw)
154
      webpage.publish()
155
      transaction.commit()
156
      self.tic()
157 158 159 160 161
      self.assertEquals(language, webpage.getLanguage())
      self.assertEquals(reference, webpage.getReference())
      self.assertEquals(version, webpage.getVersion())
      self.assertEquals('published', webpage.getValidationState())
      webpage_list.append(webpage)
162

163
    return webpage_list
164

165 166 167 168
  def test_01_WebSiteRecatalog(self, quiet=quiet, run=run_all_test):
    """
      Test that a recataloging works for Web Site documents
    """
169
    if not run: return
170 171 172
    if not quiet:
      message = '\ntest_01_WebSiteRecatalog'
      ZopeTestCase._print(message)
173

174
    self.setupWebSite()
175
    portal = self.getPortal()
176
    web_site_module = self.portal.getDefaultModule('Web Site')
177 178
    web_site = web_site_module[self.website_id]

179 180 181 182 183 184 185 186
    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.')

187
  def test_02_EditSimpleWebPage(self, quiet=quiet, run=run_all_test):
188 189
    """
      Simple Case of creating a web page.
190
    """
191
    if not run: return
192 193 194
    if not quiet:
      message = '\ntest_02_EditSimpleWebPage'
      ZopeTestCase._print(message)
195 196 197 198
    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())
199

200 201 202 203 204 205 206 207 208 209 210 211 212
  def test_02a_WebPageAsText(self, quiet=quiet, run=run_all_test):
    """
      Check if Web Page's asText() returns utf-8 string correctly and
      if it is wrapped by certian column width.
    """
    if not run: return
    if not quiet:
      message = '\ntest_02a_WebPageAsText'
      ZopeTestCase._print(message)
    # disable portal_transforms cache
    self.portal.portal_transforms.max_sec_in_cache=-1
    page = self.web_page_module.newContent(portal_type='Web Page')
    page.edit(text_content='<p>Hé Hé Hé!</p>')
213 214
    transaction.commit()
    self.tic()
215 216
    self.assertEquals('Hé Hé Hé!', page.asText().strip())
    page.edit(text_content='<p>Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé!</p>')
217 218
    transaction.commit()
    self.tic()
219 220 221
    self.assertEquals("""Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé Hé
Hé Hé Hé!""", page.asText().strip())

222
  def test_03_CreateWebSiteUser(self, quiet=quiet, run=run_all_test):
223 224 225
    """
      Create Web site User.
    """
226
    if not run: return
227 228 229 230
    if not quiet:
      message = '\ntest_03_CreateWebSiteUser'
      ZopeTestCase._print(message)
    self.setupWebSite()
231 232 233 234 235 236 237 238 239 240 241
    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]
242
    website.WebSite_createWebSiteAccount('WebSite_viewRegistrationDialog')
243

244
    transaction.commit()
245
    self.tic()
246

247 248 249 250 251 252 253 254
    # 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')

255
    # check if user account is 'loggable'
256 257 258 259
    uf = portal.acl_users
    user = uf.getUserById( kw['reference'])
    self.assertEquals(str(user),  kw['reference'])
    self.assertEquals(1, user.has_role(('Member', 'Authenticated',)))
260

261 262
  def test_04_WebPageTranslation(self, quiet=quiet, run=run_all_test):
    """
263
      Simple Case of showing the proper Web Page based on
264 265
      current user selected language in browser.
    """
266
    if not run: return
267 268 269 270 271 272 273 274 275
    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)
276

277 278 279 280 281 282 283 284 285 286
    # 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()))
287

288
    # use already created few pages in different languages with same reference
289
    # and check that we always get the right one based on selected
290 291 292
    # by us language
    for language in LANGUAGE_LIST:
      # set default language in Localizer only to check that we get
293
      # the corresponding web page for language.
294 295 296 297
      # 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())
298

299
  def test_05_WebPageTextContentSubstitutions(self, quiet=quiet, run=run_all_test):
300 301 302 303
    """
      Simple Case of showing the proper text content with and without a substitution
      mapping method.
    """
304
    if not run: return
305
    if not quiet:
306
      message = '\ntest_05_WebPageTextContentSubstituions'
307 308 309 310 311 312 313
      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()
314
    document = portal.web_page_module.newContent(portal_type='Web Page',
315
            text_content=content)
316

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    # 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)

333
  def test_06_DefaultDocumentForWebSection(self, quiet=quiet, run=run_all_test):
334 335 336 337
    """
      Testing the default document for a Web Section.

      If a Web Section has a default document defined and if that default
338 339
      document is published, then getDefaultDocumentValue on that
      web section should return the latest version in the most
340
      appropriate language of that default document.
341 342

      Note: due to generic ERP5 Web implementation this test highly depends
343
      on WebSection_geDefaulttDocumentValueList
Ivan Tyagov's avatar
Ivan Tyagov committed
344 345 346
    """
    if not run: return
    if not quiet:
347
      message = '\ntest_06_DefaultDocumentForWebSection'
348
      ZopeTestCase._print(message)
Ivan Tyagov's avatar
Ivan Tyagov committed
349 350 351 352
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    publication_section_category_id_list = ['documentation',  'administration']
353

Ivan Tyagov's avatar
Ivan Tyagov committed
354
    # create pages belonging to this publication_section 'documentation'
355
    web_page_en = portal.web_page_module.newContent(portal_type = 'Web Page',
356
                                                 id='section_home',
357 358 359
                                                 language = 'en',
                                                 reference='NXD-DDP',
                                                 publication_section_list=publication_section_category_id_list[:1])
Ivan Tyagov's avatar
Ivan Tyagov committed
360
    websection.setAggregateValue(web_page_en)
361
    transaction.commit()
Ivan Tyagov's avatar
Ivan Tyagov committed
362
    self.tic()
363
    self.assertEqual(None, websection.getDefaultDocumentValue())
Ivan Tyagov's avatar
Ivan Tyagov committed
364 365
    # publish it
    web_page_en.publish()
366
    transaction.commit()
Ivan Tyagov's avatar
Ivan Tyagov committed
367
    self.tic()
368 369 370 371 372 373 374
    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]
375
    self.assertEqual(base_url, "%s/%s/" % (websection.absolute_url(), web_page_en.getReference()))
376

377
  def test_06b_DefaultDocumentForWebSite(self, quiet=quiet, run=run_all_test):
378 379 380 381
    """
      Testing the default document for a Web Site.

      If a Web Section has a default document defined and if that default
382 383
      document is published, then getDefaultDocumentValue on that
      web section should return the latest version in the most
384
      appropriate language of that default document.
385 386

      Note: due to generic ERP5 Web implementation this test highly depends
387 388 389 390
      on WebSection_geDefaulttDocumentValueList
    """
    if not run: return
    if not quiet:
391
      message = '\ntest_06b_DefaultDocumentForWebSite'
392
      ZopeTestCase._print(message)
393 394 395
    portal = self.getPortal()
    website = self.setupWebSite()
    publication_section_category_id_list = ['documentation',  'administration']
396

397
    # create pages belonging to this publication_section 'documentation'
398
    web_page_en = portal.web_page_module.newContent(portal_type = 'Web Page',
399
                                                 id='site_home',
400 401 402
                                                 language = 'en',
                                                 reference='NXD-DDP-Site',
                                                 publication_section_list=publication_section_category_id_list[:1])
403
    website.setAggregateValue(web_page_en)
404
    transaction.commit()
405 406 407 408
    self.tic()
    self.assertEqual(None, website.getDefaultDocumentValue())
    # publish it
    web_page_en.publish()
409
    transaction.commit()
410 411 412 413 414 415 416 417
    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]
418
    self.assertEqual(base_url, "%s/%s/" % (website.absolute_url(), web_page_en.getReference()))
419

420
  def test_07_WebSection_getDocumentValueList(self, quiet=quiet, run=run_all_test):
421 422
    """ Check getting getDocumentValueList from Web Section.
    """
423
    if not run: return
424
    if not quiet:
425
      message = '\ntest_07_WebSection_getDocumentValueList'
426
      ZopeTestCase._print(message)
427 428 429 430
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    publication_section_category_id_list = ['documentation',  'administration']
431

432
    #set predicate on web section using 'publication_section'
433
    websection.edit(membership_criterion_base_category = ['publication_section'],
434 435
                     membership_criterion_category=['publication_section/%s' \
                                                    % publication_section_category_id_list[0]])
436 437 438
    # clean up
    self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
    portal.portal_categories.publication_section.manage_delObjects(
439
                                      list(portal.portal_categories.publication_section.objectIds()))
440 441
    # create categories
    for category_id in publication_section_category_id_list:
442
      portal.portal_categories.publication_section.newContent(portal_type = 'Category',
443 444
                                                              id = category_id)

445 446 447 448 449 450 451 452 453 454 455 456 457
    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"),
458 459
                      '14' : dict(language = 'ja' , version = "2" , reference = "E"),
                      '15' : dict(language = 'pt' , version = "2" , reference = "F"),
460 461
                    }
    sequence_one = property_dict.keys()
462 463 464 465
    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']
466

467
    sequence_count = 0
468
    for sequence in [ sequence_one , sequence_two , sequence_three ]:
469 470
      sequence_count += 1
      if not quiet:
471
        message = '\ntest_07_WebSection_getDocumentValueList (Sequence %s)' \
472 473 474
                                                                % (sequence_count)
        ZopeTestCase._print(message)

475
      web_page_list = []
476 477
      for key in sequence:
        web_page = self.portal.web_page_module.newContent(
478
                                  title=key,
479 480
                                  portal_type = 'Web Page',
                                  publication_section_list=publication_section_category_id_list[:1])
481

482
        web_page.edit(**property_dict[key])
483
        transaction.commit()
484 485
        self.tic()
        web_page_list.append(web_page)
486

487
      transaction.commit()
488
      self.tic()
489
      # in draft state, no documents should belong to this Web Section
490
      self.assertEqual(0, len(websection.getDocumentValueList()))
491

492
      # when published, all web pages should belong to it
493 494
      for web_page in web_page_list:
        web_page.publish()
495
      transaction.commit()
496
      self.tic()
497

498
      # Test for limit parameter
499
      self.assertEqual(2, len(websection.getDocumentValueList(limit=2)))
500 501

      # Testing for language parameter
502
      self.assertEqual(4, len(websection.getDocumentValueList()))
503
      self.assertEqual(['en' , 'en', 'en', 'en'],
504
                       [ w.getLanguage()  for w in websection.getDocumentValueList()])
505

506
      pt_document_value_list = websection.getDocumentValueList(language='pt')
507
      self.assertEqual(4, len(pt_document_value_list))
508 509
      self.assertEqual(['pt' , 'pt', 'pt', 'pt'],
                           [ w.getObject().getLanguage() for w in pt_document_value_list])
510

511
      ja_document_value_list = websection.getDocumentValueList(language='ja')
512
      self.assertEqual(4, len(ja_document_value_list))
513 514
      self.assertEqual(['ja' , 'ja', 'ja', 'ja'],
                           [ w.getLanguage() for w in ja_document_value_list])
515 516 517 518 519 520 521 522 523 524 525 526 527

      # 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])

528
      ja_document_value_list = websection.getDocumentValueList(language='ja',
529 530 531 532 533 534
                                                               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
535 536 537 538 539 540 541 542 543 544 545 546
      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'])
547

548 549 550 551 552 553 554 555 556 557 558 559 560
      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'])
561

562 563 564 565 566 567 568 569 570 571 572 573 574 575
      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'])

576
      # Tests for all_languages and all_versions
577 578 579 580 581 582 583 584 585 586 587
      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')

588
      for document_value_list in [ en_document_value_list, pt_document_value_list ,
589 590 591 592 593 594 595 596 597 598 599
                                   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
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')])])
620

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
      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')])])

636
      self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
637

638
  def test_08_AcquisitionWrappers(self, quiet=quiet, run=run_all_test):
639 640 641 642 643 644
    """Test acquisition wrappers of documents.
    Check if documents obtained by getDefaultDocumentValue, getDocumentValue
    and getDocumentValueList are wrapped appropriately.
    """
    if not run: return
    if not quiet:
645
      message = '\ntest_08_AcquisitionWrappers'
646
      ZopeTestCase._print(message)
647 648 649 650 651 652 653 654 655

    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')
656
      transaction.commit()
657 658 659 660 661 662 663
      self.tic()

    website = self.setupWebSite()
    websection = self.setupWebSection(
            membership_criterion_base_category_list=('publication_section',),
            membership_criterion_category=('publication_section/my_test_category',),
            )
664

665 666 667 668 669 670 671 672 673 674 675
    # 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])
676
    transaction.commit()
677
    self.tic()
678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    # 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)
696

697
  def test_09_WebSiteSkinSelection(self, quiet=quiet, run=run_all_test):
698 699 700 701 702
    """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:
703
      message = '\ntest_09_WebSiteSkinSelection'
704
      ZopeTestCase._print(message)
705 706 707 708 709 710 711

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

    # First, make sure that we use the default skin selection.
    portal.changeSkin(ps.getDefaultSkin())
712
    transaction.commit()
713 714 715 716 717 718 719 720 721 722 723
    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',))
724

725 726 727 728 729 730 731 732 733 734 735 736 737
    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"')

738
    transaction.commit()
739 740 741 742 743 744 745 746 747 748 749
    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')
750
    transaction.commit()
751 752 753 754 755
    self.tic()

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

756
  def test_10_getDocumentValueList(self, quiet=quiet, run=run_all_test):
757
    """Make sure that getDocumentValueList works."""
758 759 760 761
    if not run: return
    if not quiet:
      message = '\ntest_10_getDocumentValueList'
      ZopeTestCase._print(message)
762

763 764 765 766 767 768
    self.setupWebSite()
    website = self.web_site_module[self.website_id]
    website.getDocumentValueList(
      portal_type='Document',
      sort_on=[('translated_portal_type', 'ascending')])

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
  def test_11_getWebSectionValueList(self, quiet=quiet, run=run_all_test):
    """ Check getWebSectionValueList from Web Site.
    Only visible web section should be returned.
    """
    if not run: return
    if not quiet:
      message = 'test_11_getWebSectionValueList'
      ZopeTestCase._print(message)

    portal = self.getPortal()
    web_site_portal_type = 'Web Site'
    web_section_portal_type = 'Web Section'
    web_page_portal_type = 'Web Page'

    # Create web site and web section
    web_site_module = portal.getDefaultModule(web_site_portal_type)
    web_site = web_site_module.newContent(portal_type=web_site_portal_type)
    web_section = web_site.newContent(portal_type=web_section_portal_type)
    sub_web_section = web_section.newContent(portal_type=web_section_portal_type)

    # Create a document
    web_page_module = portal.getDefaultModule(web_page_portal_type)
    web_page = web_page_module.newContent(portal_type=web_page_portal_type)

    # Commit transaction
    def _commit():
      portal.portal_caches.clearAllCache()
796
      transaction.commit()
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
      self.tic()

    # By default, as now Web Section is visible, nothing should be returned
    _commit()
    self.assertSameSet([], web_site.getWebSectionValueList(web_page))

    # Explicitely set both web section invisible
    web_section.setVisible(0)
    sub_web_section.setVisible(0)
    _commit()
    self.assertSameSet([], web_site.getWebSectionValueList(web_page))

    # Set parent web section visible
    web_section.setVisible(1)
    sub_web_section.setVisible(0)
    _commit()
813
    self.assertSameSet([web_section],
814 815 816 817 818 819 820
                       web_site.getWebSectionValueList(web_page))

    # Set both web section visible
    # Only leaf web section is returned
    web_section.setVisible(1)
    sub_web_section.setVisible(1)
    _commit()
821
    self.assertSameSet([sub_web_section],
822 823
                       web_site.getWebSectionValueList(web_page))

Romain Courteaud's avatar
Romain Courteaud committed
824 825
    # Set leaf web section visible, which should be returned even if parent is
    # not visible
826 827 828
    web_section.setVisible(0)
    sub_web_section.setVisible(1)
    _commit()
829
    self.assertSameSet([sub_web_section],
830 831
                       web_site.getWebSectionValueList(web_page))

832 833
  def test_12_getWebSiteValue(self, quiet=quiet, run=run_all_test):
    """
834 835
      Test that getWebSiteValue() and getWebSectionValue() always
      include selected Language.
836 837 838 839 840 841
    """
    if not run: return
    if not quiet:
      message = '\ntest_12_getWebSiteValue'
      ZopeTestCase._print(message)

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    website_id = self.setupWebSite().getId()
    website = self.portal.restrictedTraverse(
      'web_site_module/%s' % website_id)
    website_relative_url = website.absolute_url(relative=1)
    website_fr = self.portal.restrictedTraverse(
      'web_site_module/%s/fr' % website_id)
    website_relative_url_fr = '%s/fr' % website_relative_url

    websection_id = self.setupWebSection().getId()
    websection = self.portal.restrictedTraverse(
      'web_site_module/%s/%s' % (website_id, websection_id))
    websection_relative_url = websection.absolute_url(relative=1)
    websection_fr = self.portal.restrictedTraverse(
      'web_site_module/%s/fr/%s' % (website_id, websection_id))
    websection_relative_url_fr = '%s/%s' % (website_relative_url_fr,
                                            websection.getId())

    page_ref = 'foo'
860 861 862 863 864 865 866
    page = self.web_page_module.newContent(portal_type='Web Page',
                                           reference='foo',
                                           text_content='<b>OK</b>')
    page.publish()
    transaction.commit()
    self.tic()

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
    webpage = self.portal.restrictedTraverse(
      'web_site_module/%s/%s' % (website_id, page_ref))
    webpage_fr = self.portal.restrictedTraverse(
      'web_site_module/%s/fr/%s' % (website_id, page_ref))

    webpage_module = self.portal.restrictedTraverse(
      'web_site_module/%s/web_page_module' % website_id)
    webpage_module_fr = self.portal.restrictedTraverse(
      'web_site_module/%s/fr/web_page_module' % website_id)

    self.assertEquals(website_relative_url,
                      website.getWebSiteValue().absolute_url(relative=1))
    self.assertEquals(website_relative_url_fr,
                      website_fr.getWebSiteValue().absolute_url(relative=1))
    self.assertEquals(website_relative_url,
                      webpage.getWebSiteValue().absolute_url(relative=1))
    self.assertEquals(website_relative_url_fr,
                      webpage_fr.getWebSiteValue().absolute_url(relative=1))
    self.assertEquals(website_relative_url,
                      webpage_module.getWebSiteValue().absolute_url(relative=1))
    self.assertEquals(website_relative_url_fr,
                      webpage_module_fr.getWebSiteValue().absolute_url(relative=1))

    webpage = self.portal.restrictedTraverse(
      'web_site_module/%s/%s/%s' % (website_id, websection_id, page_ref))
    webpage_fr = self.portal.restrictedTraverse(
      'web_site_module/%s/fr/%s/%s' % (website_id, websection_id, page_ref))

    webpage_module = self.portal.restrictedTraverse(
      'web_site_module/%s/%s/web_page_module' % (website_id, websection_id))
    webpage_module_fr = self.portal.restrictedTraverse(
      'web_site_module/%s/fr/%s/web_page_module' % (website_id, websection_id))

    self.assertEquals(websection_relative_url,
                      websection.getWebSectionValue().absolute_url(relative=1))
    self.assertEquals(websection_relative_url_fr,
                      websection_fr.getWebSectionValue().absolute_url(relative=1))
    self.assertEquals(websection_relative_url,
                      webpage.getWebSectionValue().absolute_url(relative=1))
    self.assertEquals(websection_relative_url_fr,
                      webpage_fr.getWebSectionValue().absolute_url(relative=1))
    self.assertEquals(websection_relative_url,
                      webpage_module.getWebSectionValue().absolute_url(relative=1))
    self.assertEquals(websection_relative_url_fr,
                      webpage_module_fr.getWebSectionValue().absolute_url(relative=1))
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
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'])
942
    self.createUser('webmaster', ['Assignor'])
943
    transaction.commit()
944 945
    self.tic()

946 947
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
948
    transaction.commit()
949 950
    self.tic()

951
  def beforeTearDown(self):
952 953
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
954

955
  def test_01_AccessWebPageByReference(self, quiet=quiet, run=run_all_test):
956 957 958 959 960
    if not run: return
    if not quiet:
      message = '\ntest_01_AccessWebPageByReference'
      ZopeTestCase._print(message)

961 962 963 964 965
    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')

966
    transaction.commit()
967 968 969 970 971
    self.tic()

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

972
    transaction.commit()
973 974 975 976 977 978 979 980 981 982
    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!')

983
    transaction.commit()
984 985 986 987
    self.tic()

    page_en.publish()

988
    transaction.commit()
989 990 991 992 993 994 995 996 997
    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='こんにちは、世界!')

998
    transaction.commit()
999 1000 1001 1002
    self.tic()

    page_ja.publish()

1003
    transaction.commit()
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
    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())
1018

1019 1020
  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 . """
1021 1022 1023 1024
    if not run: return
    if not quiet:
      message = '\ntest_02_LocalRolesFromRoleDefinition'
      ZopeTestCase._print(message)
1025 1026 1027 1028 1029
    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')
1030
    person = portal.person_module.newContent(portal_type = 'Person',
1031
                                             reference = person_reference)
1032
    # add Role Definition for site and section
1033 1034
    site_role_definition = site.newContent(portal_type = 'Role Definition',
                                           role_name = 'Assignee',
1035
                                           agent = person.getRelativeUrl())
1036 1037
    section_role_definition = section.newContent(portal_type = 'Role Definition',
                                                 role_name = 'Associate',
1038
                                                 agent = person.getRelativeUrl())
1039
    transaction.commit()
1040 1041
    self.tic()
    # check if Role Definition have create local roles
1042
    self.assertSameSet(('Assignee',),
1043
                          site.get_local_roles_for_userid(person_reference))
1044
    self.assertSameSet(('Associate',),
1045
                          section.get_local_roles_for_userid(person_reference))
1046 1047
    self.assertRaises(Unauthorized, site_role_definition.edit,
                      role_name='Manager')
1048

1049 1050 1051
    # 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())
1052
    transaction.commit()
1053
    self.tic()
1054
    self.assertSameSet((),
1055 1056 1057 1058 1059 1060
                       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"""
1061 1062 1063 1064
    if not run: return
    if not quiet:
      message = '\ntest_03_WebSection_getDocumentValueListSecurity'
      ZopeTestCase._print(message)
1065 1066 1067 1068 1069
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module
    site = web_site_module.newContent(portal_type='Web Site',
                                      id='site')

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

1073
    transaction.commit()
1074 1075 1076
    self.tic()

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

1080
    transaction.commit()
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    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!')

1112
    transaction.commit()
1113 1114 1115
    self.changeUser('erp5user')
    self.tic()
    self.portal.Localizer.changeLanguage('en')
1116

1117
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))
1118 1119 1120

    self.changeUser('erp5user')
    page_en_0.publish()
1121
    transaction.commit()
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    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()))
1136
    self.assertEquals(page_en_0.getUid(),
1137 1138 1139 1140 1141 1142 1143
                      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()
1144
    transaction.commit()
1145 1146 1147 1148
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
1149
    self.assertEquals(page_en_1.getUid(),
1150 1151 1152 1153 1154 1155 1156 1157
                      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()))
1158
    self.assertEquals(page_en_1.getUid(),
1159 1160 1161 1162 1163
                      section.WebSection_getDocumentValueList()[0].getUid())

    # Trird Object
    self.changeUser('erp5user')
    page_en_2.publish()
1164
    transaction.commit()
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    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()))

1179
    # First Japanese Object
1180 1181
    self.changeUser('erp5user')
    page_jp_0.publish()
1182
    transaction.commit()
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    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()))
1196
    self.assertEquals(page_jp_0.getUid(),
1197
                      section.WebSection_getDocumentValueList()[0].getUid())
1198

1199 1200 1201 1202 1203 1204
  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)
1205

1206 1207
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module
1208 1209 1210 1211 1212 1213 1214 1215 1216
    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')
1217
    transaction.commit()
1218 1219
    self.tic()

1220 1221 1222 1223 1224 1225
    # 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.")
1226

1227
    # test if a user (ASSIGNOR) can expire them
1228
    self.changeUser('webmaster')
1229 1230 1231 1232 1233
    try:
      section_2.expire()
      section_6.expire()
    except Unauthorized:
      self.fail("An user should be able to expire a Web Section.")
1234

1235
  def test_05_createWebSite(self, quiet=quiet, run=run_all_test):
1236
    """ Test to create or clone web sites with many users """
1237 1238 1239 1240
    if not run: return
    if not quiet:
      message = '\ntest_05_createWebSite'
      ZopeTestCase._print(message)
1241

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module

    # test for admin
    try:
      site_1 = web_site_module.newContent(portal_type='Web Site', id='site_1')
    except Unauthorized:
      self.fail("Admin should be able to create a Web Site.")

    # test as a web user (assignor)
1252
    self.changeUser('webmaster')
1253 1254 1255 1256 1257
    try:
      site_2 = web_site_module.newContent(portal_type='Web Site', id='site_2')
    except Unauthorized:
      self.fail("A webmaster should be able to create a Web Site.")

1258 1259 1260 1261 1262
    site_2_copy = web_site_module.manage_copyObjects(ids=(site_2.getId(),))
    site_2_clone = web_site_module[web_site_module.manage_pasteObjects(
      site_2_copy)[0]['new_id']]
    self.assertEquals(site_2_clone.getPortalType(), 'Web Site')

1263
  def test_06_createWebSection(self, quiet=quiet, run=run_all_test):
1264
    """ Test to create or clone web sections with many users """
1265 1266
    if not run: return
    if not quiet:
1267
      message = '\ntest_06_createWebSection'
1268
      ZopeTestCase._print(message)
1269

1270 1271 1272
    self.changeUser('admin')
    web_site_module = self.portal.web_site_module
    site = web_site_module.newContent(portal_type='Web Site', id='site')
1273

1274 1275 1276 1277 1278 1279 1280
    # 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.")

1281 1282
    # test as a webmaster (assignor)
    self.changeUser('webmaster')
1283 1284 1285 1286
    try:
      section_2 = site.newContent(portal_type='Web Section', id='section_2')
      section_3 = section_2.newContent(portal_type='Web Section', id='section_3')
    except Unauthorized:
1287
      self.fail("A webmaster should be able to create a Web Section.")
1288 1289 1290 1291 1292 1293 1294 1295
    section_2_copy = site.manage_copyObjects(ids=(section_2.getId(),))
    section_2_clone = site[site.manage_pasteObjects(
      section_2_copy)[0]['new_id']]
    self.assertEquals(section_2_clone.getPortalType(), 'Web Section')
    section_3_copy = section_2.manage_copyObjects(ids=(section_3.getId(),))
    section_3_clone = section_2[section_2.manage_pasteObjects(
      section_3_copy)[0]['new_id']]
    self.assertEquals(section_3_clone.getPortalType(), 'Web Section')
1296

1297 1298 1299 1300 1301 1302
  def test_07_createCategory(self, quiet=quiet, run=run_all_test):
    """ Test to create or clone categories with many users """
    if not run: return
    if not quiet:
      message = '\ntest_07_createCategory'
      ZopeTestCase._print(message)
1303

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    self.changeUser('admin')
    portal_categories = self.portal.portal_categories
    publication_section = portal_categories.publication_section

    # test for admin
    try:
      base_category_1 = portal_categories.newContent(portal_type='Base Category', id='base_category_1')
    except Unauthorized:
      self.fail("Admin should be able to create a Base Category.")
    try:
      category_1 = publication_section.newContent(portal_type='Category', id='category_1')
      category_2 = category_1.newContent(portal_type='Category', id='category_3')
    except Unauthorized:
      self.fail("Admin should be able to create a Category.")
    category_1_copy = publication_section.manage_copyObjects(ids=(category_1.getId(),))
    category_1_clone = publication_section[publication_section.manage_pasteObjects(
      category_1_copy)[0]['new_id']]
    self.assertEquals(category_1_clone.getPortalType(), 'Category')
    category_2_copy = category_1.manage_copyObjects(ids=(category_2.getId(),))
    category_2_clone = category_1[category_1.manage_pasteObjects(
      category_2_copy)[0]['new_id']]
    self.assertEquals(category_2_clone.getPortalType(), 'Category')

    # test as a web user (assignor)
1328
    self.changeUser('webmaster')
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
    try:
      base_category_2 = portal_categories.newContent(portal_type='Base Category', id='base_category_2')
      self.fail("A webmaster should not be able to create a Base Category.")
    except Unauthorized:
      pass
    try:
      category_3 = publication_section.newContent(portal_type='Category', id='category_3')
      category_4 = category_3.newContent(portal_type='Category', id='category_4')
    except Unauthorized:
      self.fail("A webmaster should be able to create a Category.")
    # try to clone a sub category of the same owner whose parent is a
    # base category.
    category_3_copy = publication_section.manage_copyObjects(ids=(category_3.getId(),))
    category_3_clone = publication_section[publication_section.manage_pasteObjects(
      category_3_copy)[0]['new_id']]
    self.assertEquals(category_3_clone.getPortalType(), 'Category')
    # try to clone a sub category of the different owner
    category_2_copy = category_1.manage_copyObjects(ids=(category_2.getId(),))
    category_2_clone = category_1[category_1.manage_pasteObjects(
      category_2_copy)[0]['new_id']]
    self.assertEquals(category_2_clone.getPortalType(), 'Category')
    # try to clone a sub category of the same owner
    category_4_copy = category_3.manage_copyObjects(ids=(category_4.getId(),))
    category_4_clone = category_3[category_3.manage_pasteObjects(
      category_4_copy)[0]['new_id']]
    self.assertEquals(category_4_clone.getPortalType(), 'Category')
1355

1356 1357 1358 1359 1360 1361
  def test_08_createAndrenameCategory(self, quiet=quiet, run=run_all_test):
    """ Test to create or rename categories with many users """
    if not run: return
    if not quiet:
      message = '\ntest_08_createAndrenameCategory'
      ZopeTestCase._print(message)
1362

1363 1364 1365
    self.changeUser('admin')
    portal_categories = self.portal.portal_categories
    publication_section = portal_categories.publication_section
1366

1367 1368 1369 1370 1371 1372 1373 1374
    # test for admin
    try:
      new_base_category_1 = portal_categories.newContent(portal_type='Base Category', id='new_base_category_1')
    except Unauthorized:
      self.fail("Admin should be able to create a Base Category.")
    try:
      new_category_1 = publication_section.newContent(portal_type='Category', id='new_category_1')
      new_category_2 = new_category_1.newContent(portal_type='Category',
1375
      id='new_category_2')
1376 1377
    except Unauthorized:
      self.fail("Admin should be able to create a Category.")
1378
    transaction.commit()
1379 1380
    self.tic()
    try:
1381
      new_cat_1_renamed = new_category_1.edit(id='new_cat_1_renamed')
1382 1383 1384 1385
      new_cat_2_renamed = new_category_2.edit(id='new_cat_2_renamed')
    except Unauthorized:
      self.fail("Admin should be able to rename a Category.")
    # test as a web user (assignor)
1386
    self.changeUser('webmaster')
1387 1388 1389 1390 1391 1392 1393 1394 1395
    try:
      base_category_2 = portal_categories.newContent(portal_type='Base Category', id='base_category_2')
      self.fail("A webmaster should not be able to create a Base Category.")
    except Unauthorized:
      pass
    try:
      new_category_3 = publication_section.newContent(
      portal_type='Category',id='new_category_3')
      new_category_4 = new_category_3.newContent(portal_type='Category',
1396
          id='new_category_4')
1397 1398
    except Unauthorized:
      self.fail("A webmaster should be able to create a Category.")
1399
    transaction.commit()
1400 1401
    self.tic()
    try:
1402
      new_cat_3_renamed = new_category_3.edit(id='new_cat_3_renamed')
1403 1404 1405
      new_cat_4_renamed = new_category_4.edit(id='new_cat_4_renamed')
    except Unauthorized:
      self.fail("A webmaster should be able to rename a Category.")
1406

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
class TestERP5WebCategoryPublicationWorkflow(ERP5TypeTestCase):
  """Tests possible transitions for category_publication_workflow"""
  def getBusinessTemplateList(self):
    return ('erp5_base',
            'erp5_web',
            )

  def afterSetUp(self):
    base_category = self.getPortal().portal_categories\
        .newContent(portal_type='Base Category')
    self.doActionFor = self.getPortal().portal_workflow.doActionFor
    self.category = base_category.newContent(portal_type='Category')
    self.assertEqual('embedded', self.category.getValidationState())

  def test_category_embedded_expired(self):
    self.doActionFor(self.category, 'expire_action')
    self.assertEqual('expired', self.category.getValidationState())

  def test_category_embedded_protected_expired(self):
    self.doActionFor(self.category, 'protect_action')
    self.assertEqual('protected', self.category.getValidationState())
    self.doActionFor(self.category, 'expire_action')
    self.assertEqual('expired_protected', self.category.getValidationState())

  def test_category_embedded_published_expired(self):
    self.doActionFor(self.category, 'publish_action')
    self.assertEqual('published', self.category.getValidationState())
    self.doActionFor(self.category, 'expire_action')
    self.assertEqual('expired_published', self.category.getValidationState())

1437 1438 1439
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Web))
1440
  suite.addTest(unittest.makeSuite(TestERP5WebWithSimpleSecurity))
1441
  suite.addTest(unittest.makeSuite(TestERP5WebCategoryPublicationWorkflow))
1442
  return suite