testERP5Web.py 64.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 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
class TestERP5Web(ERP5TypeTestCase):
46 47
  """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 59 60

  def getTitle(self):
    return "ERP5Web"

  def getBusinessTemplateList(self):
    """
    Return the list of required business templates.
    """
61 62 63
    return ('erp5_base',
            'erp5_web',
            )
64 65

  def afterSetUp(self):
66
    portal = self.getPortal()
67 68 69 70 71

    uf = portal.acl_users
    uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
    self.login(self.manager_username)

72 73
    self.web_page_module = self.portal.getDefaultModule('Web Page Module')
    self.web_site_module = self.portal.getDefaultModule('Web Site Module')
74
    portal.Localizer.manage_changeDefaultLang(language = 'en')
75 76
    self.portal_id = self.portal.getId()

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

82
  def beforeTearDown(self):
83 84
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
85
    self.clearModule(self.portal.person_module)
86

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

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

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

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

126
    transaction.commit()
127 128 129
    self.tic()
    return websection

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

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

161
    return webpage_list
162

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

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

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

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

198 199 200 201 202 203 204 205 206 207 208
  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
209 210 211
    # use w3m dump explicitly
    self.portal.portal_transforms.manage_addPolicy(output_mimetype='text/plain',
                                                   required_transforms=['w3m_dump'])
212 213
    page = self.web_page_module.newContent(portal_type='Web Page')
    page.edit(text_content='<p>Hé Hé Hé!</p>')
214 215
    transaction.commit()
    self.tic()
216 217
    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>')
218 219
    transaction.commit()
    self.tic()
220 221 222
    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())

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

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

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

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

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

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

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

300
  def test_05_WebPageTextContentSubstitutions(self, quiet=quiet, run=run_all_test):
301 302 303
    """
      Simple Case of showing the proper text content with and without a substitution
      mapping method.
304
      In case of asText, the content should be replaced too
305
    """
306
    if not run: return
307
    if not quiet:
308
      message = '\ntest_05_WebPageTextContentSubstitutions'
309 310 311
      ZopeTestCase._print(message)

    content = '<a href="${toto}">$titi</a>'
312
    asText_content = '$titi\n'
313
    substituted_content = '<a href="foo">bar</a>'
314
    substituted_asText_content = 'bar\n'
315 316 317
    mapping = dict(toto='foo', titi='bar')

    portal = self.getPortal()
318
    document = portal.web_page_module.newContent(portal_type='Web Page',
319
            text_content=content)
320

321 322
    # No substitution should occur.
    self.assertEquals(document.asStrippedHTML(), content)
323
    self.assertEquals(document.asText(), asText_content)
324 325 326 327 328 329 330

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

    # Substitutions should occur.
    self.assertEquals(document.asStrippedHTML(), substituted_content)
331
    self.assertEquals(document.asText(), substituted_asText_content)
332 333 334 335 336 337 338

    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)

339
  def test_06_DefaultDocumentForWebSection(self, quiet=quiet, run=run_all_test):
340 341 342 343
    """
      Testing the default document for a Web Section.

      If a Web Section has a default document defined and if that default
344 345
      document is published, then getDefaultDocumentValue on that
      web section should return the latest version in the most
346
      appropriate language of that default document.
347 348

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

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

383
  def test_06b_DefaultDocumentForWebSite(self, quiet=quiet, run=run_all_test):
384 385 386 387
    """
      Testing the default document for a Web Site.

      If a Web Section has a default document defined and if that default
388 389
      document is published, then getDefaultDocumentValue on that
      web section should return the latest version in the most
390
      appropriate language of that default document.
391 392

      Note: due to generic ERP5 Web implementation this test highly depends
393 394 395 396
      on WebSection_geDefaulttDocumentValueList
    """
    if not run: return
    if not quiet:
397
      message = '\ntest_06b_DefaultDocumentForWebSite'
398
      ZopeTestCase._print(message)
399 400 401
    portal = self.getPortal()
    website = self.setupWebSite()
    publication_section_category_id_list = ['documentation',  'administration']
402

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

426
  def test_07_WebSection_getDocumentValueList(self, quiet=quiet, run=run_all_test):
427 428
    """ Check getting getDocumentValueList from Web Section.
    """
429
    if not run: return
430
    if not quiet:
431
      message = '\ntest_07_WebSection_getDocumentValueList'
432
      ZopeTestCase._print(message)
433 434 435 436
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    publication_section_category_id_list = ['documentation',  'administration']
437

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

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

473
    sequence_count = 0
474
    for sequence in [ sequence_one , sequence_two , sequence_three ]:
475 476
      sequence_count += 1
      if not quiet:
477
        message = '\ntest_07_WebSection_getDocumentValueList (Sequence %s)' \
478 479 480
                                                                % (sequence_count)
        ZopeTestCase._print(message)

481
      web_page_list = []
482 483
      for key in sequence:
        web_page = self.portal.web_page_module.newContent(
484
                                  title=key,
485 486
                                  portal_type = 'Web Page',
                                  publication_section_list=publication_section_category_id_list[:1])
487

488
        web_page.edit(**property_dict[key])
489
        transaction.commit()
490 491
        self.tic()
        web_page_list.append(web_page)
492

493
      transaction.commit()
494
      self.tic()
495
      # in draft state, no documents should belong to this Web Section
496
      self.assertEqual(0, len(websection.getDocumentValueList()))
497

498
      # when published, all web pages should belong to it
499 500
      for web_page in web_page_list:
        web_page.publish()
501
      transaction.commit()
502
      self.tic()
503

504
      # Test for limit parameter
505
      self.assertEqual(2, len(websection.getDocumentValueList(limit=2)))
506 507

      # Testing for language parameter
508
      self.assertEqual(4, len(websection.getDocumentValueList()))
509
      self.assertEqual(['en' , 'en', 'en', 'en'],
510
                       [ w.getLanguage()  for w in websection.getDocumentValueList()])
511

512
      pt_document_value_list = websection.getDocumentValueList(language='pt')
513
      self.assertEqual(4, len(pt_document_value_list))
514 515
      self.assertEqual(['pt' , 'pt', 'pt', 'pt'],
                           [ w.getObject().getLanguage() for w in pt_document_value_list])
516

517
      ja_document_value_list = websection.getDocumentValueList(language='ja')
518
      self.assertEqual(4, len(ja_document_value_list))
519 520
      self.assertEqual(['ja' , 'ja', 'ja', 'ja'],
                           [ w.getLanguage() for w in ja_document_value_list])
521 522 523 524 525 526 527 528 529 530 531 532 533

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

534
      ja_document_value_list = websection.getDocumentValueList(language='ja',
535 536 537 538 539 540
                                                               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
541 542 543 544 545 546 547 548 549 550 551 552
      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'])
553

554 555 556 557 558 559 560 561 562 563 564 565 566
      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'])
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581
      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'])

582
      # Tests for all_languages and all_versions
583 584 585 586 587 588 589 590 591 592 593
      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')

594
      for document_value_list in [ en_document_value_list, pt_document_value_list ,
595 596 597 598 599 600 601 602 603 604 605
                                   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
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
      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')])])
626

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
      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')])])

642
      self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
643

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

    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')
662
      transaction.commit()
663 664 665 666 667 668 669
      self.tic()

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

671 672 673 674 675 676 677 678 679 680 681
    # 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])
682
    transaction.commit()
683
    self.tic()
684

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    # 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)
702

703
  def test_09_WebSiteSkinSelection(self, quiet=quiet, run=run_all_test):
704 705 706 707 708
    """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:
709
      message = '\ntest_09_WebSiteSkinSelection'
710
      ZopeTestCase._print(message)
711 712 713 714 715 716 717

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

    # First, make sure that we use the default skin selection.
    portal.changeSkin(ps.getDefaultSkin())
718
    transaction.commit()
719 720 721 722 723 724 725 726 727 728 729
    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',))
730

731 732 733 734 735 736 737 738 739 740 741 742 743
    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"')

744
    transaction.commit()
745 746 747 748 749 750 751 752 753 754 755
    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')
756
    transaction.commit()
757 758 759 760 761
    self.tic()

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

762
  def test_10_getDocumentValueList(self, quiet=quiet, run=run_all_test):
763
    """Make sure that getDocumentValueList works."""
764 765 766 767
    if not run: return
    if not quiet:
      message = '\ntest_10_getDocumentValueList'
      ZopeTestCase._print(message)
768

769 770 771 772 773 774
    self.setupWebSite()
    website = self.web_site_module[self.website_id]
    website.getDocumentValueList(
      portal_type='Document',
      sort_on=[('translated_portal_type', 'ascending')])

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
  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()
802
      transaction.commit()
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
      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()
819
    self.assertSameSet([web_section],
820 821 822 823 824 825 826
                       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()
827
    self.assertSameSet([sub_web_section],
828 829
                       web_site.getWebSectionValueList(web_page))

Romain Courteaud's avatar
Romain Courteaud committed
830 831
    # Set leaf web section visible, which should be returned even if parent is
    # not visible
832 833 834
    web_section.setVisible(0)
    sub_web_section.setVisible(1)
    _commit()
835
    self.assertSameSet([sub_web_section],
836 837
                       web_site.getWebSectionValueList(web_page))

838 839
  def test_12_getWebSiteValue(self, quiet=quiet, run=run_all_test):
    """
840 841
      Test that getWebSiteValue() and getWebSectionValue() always
      include selected Language.
842 843 844 845 846 847
    """
    if not run: return
    if not quiet:
      message = '\ntest_12_getWebSiteValue'
      ZopeTestCase._print(message)

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    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'
866 867 868 869 870 871 872
    page = self.web_page_module.newContent(portal_type='Web Page',
                                           reference='foo',
                                           text_content='<b>OK</b>')
    page.publish()
    transaction.commit()
    self.tic()

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 912 913 914 915 916 917
    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))
918

919 920 921 922 923 924 925 926 927 928 929 930 931 932
  def test_13_DocumentCache(self, quiet=quiet, run=run_all_test):
    """
      Test that when a document is modified, it can be accessed throug a
      web_site, a web_section or wathever and display the last content (not an
      old cache value of the document).
    """
    if not run: return
    if not quiet:
      message = '\ntest_13_DocumentCache'
      ZopeTestCase._print(message)

    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
933 934 935
    # use w3m dump explicitly
    self.portal.portal_transforms.manage_addPolicy(output_mimetype='text/plain',
                                                   required_transforms=['w3m_dump'])
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    website = self.setupWebSite()
    web_section_portal_type = 'Web Section'
    web_section = website.newContent(portal_type=web_section_portal_type)

    content = '<p>initial text</p>'
    new_content = '<p>modified text<p>'
    document = portal.web_page_module.newContent(portal_type='Web Page',
            id='document_cache',
            reference='NXD-Document.Cache',
            text_content=content)
    document.publish()
    transaction.commit()
    self.tic()
    self.assertEquals(document.asText().strip(), 'initial text')

    # Throug the web_site.
    path = website.absolute_url_path() + '/NXD-Document.Cache'
    self.assertNotEquals(request.traverse(path)(REQUEST=request.REQUEST,
      RESPONSE=request.RESPONSE).find(content), -1)

    # Throug a web_section.
    path = web_section.absolute_url_path() + '/NXD-Document.Cache'
    self.assertNotEquals(request.traverse(path)(REQUEST=request.REQUEST,
      RESPONSE=request.RESPONSE).find(content), -1)

    # modified the web_page content
    document.edit(text_content=new_content)
    self.assertEquals(document.asText().strip(), 'modified text')
    transaction.commit()
    self.tic()

    # check the cache don't send again the old content
    # Throug the web_site.
    path = website.absolute_url_path() + '/NXD-Document.Cache'
    self.assertNotEquals(request.traverse(path)(REQUEST=request.REQUEST,
      RESPONSE=request.RESPONSE).find(new_content), -1)

    # Throug a web_section.
    path = web_section.absolute_url_path() + '/NXD-Document.Cache'
    self.assertNotEquals(request.traverse(path)(REQUEST=request.REQUEST,
      RESPONSE=request.RESPONSE).find(new_content), -1)

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 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  def test_14_AccessWebSiteForWithDifferentUserPreferences(self):
    """Check that Ram Cache Manager do not mix websection
    rendering between users.
    This test enable different preferences per users and check that
    those preferences doesn't affect rendering for other users.
    user          | preference

    administrator | developper_mode activated
    webeditor     | translator_mode activated
    anonymous     | developper_mode & translator_mode disabled

    The Signature used to detect enabled preferences in HTML Body are
    manage_main for developper_mode
    manage_messages for translator_mode
    """
    user = self.createUser('administrator')
    self.createUserAssignement(user, {})
    user = self.createUser('webeditor')
    self.createUserAssignement(user, {})
    transaction.commit()
    self.tic()
    preference_tool = self.getPreferenceTool()
    isTransitionPossible = self.portal.portal_workflow.isTransitionPossible

    #create or edit preference for administrator
    administrator_preference = self.portal.portal_catalog.getResultValue(
                                                 portal_type='Preference',
                                                 owner='administrator')
    if administrator_preference is None:
      self.login('administrator')
      administrator_preference = preference_tool.newContent(
                                              portal_type='Preference')
    if isTransitionPossible(administrator_preference, 'enable_action'):
      administrator_preference.enable()

    administrator_preference.setPreferredHtmlStyleDevelopperMode(True)
    administrator_preference.setPreferredHtmlStyleTranslatorMode(False)

    #create or edit preference for webeditor
    webeditor_preference = self.portal.portal_catalog.getResultValue(
                                                  portal_type='Preference',
                                                  owner='webeditor')
    if webeditor_preference is None:
      self.login('webeditor')
      webeditor_preference = preference_tool.newContent(
                                              portal_type='Preference')
    if isTransitionPossible(webeditor_preference, 'enable_action'):
      webeditor_preference.enable()

    webeditor_preference.setPreferredHtmlStyleDevelopperMode(False)
    webeditor_preference.setPreferredHtmlStyleTranslatorMode(True)
    self.login()
    transaction.commit()
    self.tic()

    web_site = self.setupWebSite()
    websection = self.setupWebSection()

    websection_url = '%s/%s' % (self.portal.getId(), websection.getRelativeUrl())

    #connect as administrator and check that only developper_mode is enable
    response = self.publish(websection_url, 'administrator:administrator')
    self.assertTrue('manage_main' in response.getBody())
    self.assertTrue('manage_messages' not in response.getBody())

    #connect as webeditor and check that only translator_mode is enable
    response = self.publish(websection_url, 'webeditor:webeditor')
    self.assertTrue('manage_main' not in response.getBody())
    self.assertTrue('manage_messages' in response.getBody())

    #anonymous user doesn't exists, check anonymous access without preferences
    response = self.publish(websection_url, 'anonymous:anonymous')
    self.assertTrue('manage_main' not in response.getBody())
    self.assertTrue('manage_messages' not in response.getBody())


1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
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 afterSetUp(self):
    self.portal.Localizer = DummyLocalizer()
    self.createUser('admin', ['Manager'])
    self.createUser('erp5user', ['Auditor', 'Author'])
1077
    self.createUser('webmaster', ['Assignor'])
1078
    transaction.commit()
1079 1080
    self.tic()

1081 1082
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
1083
    transaction.commit()
1084 1085
    self.tic()

1086
  def beforeTearDown(self):
1087 1088
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
1089

1090
  def test_01_AccessWebPageByReference(self, quiet=quiet, run=run_all_test):
1091 1092 1093 1094 1095
    if not run: return
    if not quiet:
      message = '\ntest_01_AccessWebPageByReference'
      ZopeTestCase._print(message)

1096
    self.login('admin')
1097 1098 1099 1100
    site = self.portal.web_site_module.newContent(portal_type='Web Site',
                                                  id='site')
    section = site.newContent(portal_type='Web Section', id='section')

1101
    transaction.commit()
1102 1103 1104 1105 1106
    self.tic()

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

1107
    transaction.commit()
1108 1109
    self.tic()

1110
    self.login('erp5user')
1111 1112 1113 1114 1115 1116 1117
    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!')

1118
    transaction.commit()
1119 1120 1121 1122
    self.tic()

    page_en.publish()

1123
    transaction.commit()
1124 1125 1126 1127 1128 1129 1130 1131 1132
    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='こんにちは、世界!')

1133
    transaction.commit()
1134 1135 1136 1137
    self.tic()

    page_ja.publish()

1138
    transaction.commit()
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    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())
1153

1154 1155
  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 . """
1156 1157 1158 1159
    if not run: return
    if not quiet:
      message = '\ntest_02_LocalRolesFromRoleDefinition'
      ZopeTestCase._print(message)
1160 1161 1162 1163 1164
    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')
1165
    person = portal.person_module.newContent(portal_type = 'Person',
1166
                                             reference = person_reference)
1167
    # add Role Definition for site and section
1168 1169
    site_role_definition = site.newContent(portal_type = 'Role Definition',
                                           role_name = 'Assignee',
1170
                                           agent = person.getRelativeUrl())
1171 1172
    section_role_definition = section.newContent(portal_type = 'Role Definition',
                                                 role_name = 'Associate',
1173
                                                 agent = person.getRelativeUrl())
1174
    transaction.commit()
1175 1176
    self.tic()
    # check if Role Definition have create local roles
1177
    self.assertSameSet(('Assignee',),
1178
                          site.get_local_roles_for_userid(person_reference))
1179
    self.assertSameSet(('Associate',),
1180
                          section.get_local_roles_for_userid(person_reference))
1181 1182
    self.assertRaises(Unauthorized, site_role_definition.edit,
                      role_name='Manager')
1183

1184 1185 1186
    # 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())
1187
    transaction.commit()
1188
    self.tic()
1189
    self.assertSameSet((),
1190 1191 1192 1193 1194 1195
                       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"""
1196 1197 1198 1199
    if not run: return
    if not quiet:
      message = '\ntest_03_WebSection_getDocumentValueListSecurity'
      ZopeTestCase._print(message)
1200
    self.login('admin')
1201 1202 1203 1204
    web_site_module = self.portal.web_site_module
    site = web_site_module.newContent(portal_type='Web Site',
                                      id='site')

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

1208
    transaction.commit()
1209 1210 1211
    self.tic()

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

1215
    transaction.commit()
1216 1217
    self.tic()

1218
    self.login('erp5user')
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    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!')

1247
    transaction.commit()
1248
    self.login('erp5user')
1249 1250
    self.tic()
    self.portal.Localizer.changeLanguage('en')
1251

1252
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))
1253

1254
    self.login('erp5user')
1255
    page_en_0.publish()
1256
    transaction.commit()
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    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()))
1271
    self.assertEquals(page_en_0.getUid(),
1272 1273 1274 1275 1276
                      section.WebSection_getDocumentValueList()[0].getUid())
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # Second Object
1277
    self.login('erp5user')
1278
    page_en_1.publish()
1279
    transaction.commit()
1280 1281 1282 1283
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
1284
    self.assertEquals(page_en_1.getUid(),
1285 1286 1287 1288 1289 1290 1291 1292
                      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()))
1293
    self.assertEquals(page_en_1.getUid(),
1294 1295 1296
                      section.WebSection_getDocumentValueList()[0].getUid())

    # Trird Object
1297
    self.login('erp5user')
1298
    page_en_2.publish()
1299
    transaction.commit()
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    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()))

1314
    # First Japanese Object
1315
    self.login('erp5user')
1316
    page_jp_0.publish()
1317
    transaction.commit()
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    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()))
1331
    self.assertEquals(page_jp_0.getUid(),
1332
                      section.WebSection_getDocumentValueList()[0].getUid())
1333

1334 1335 1336 1337 1338 1339
  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)
1340

1341
    self.login('admin')
1342
    web_site_module = self.portal.web_site_module
1343 1344 1345 1346 1347 1348 1349 1350 1351
    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')
1352
    transaction.commit()
1353 1354
    self.tic()

1355 1356 1357 1358 1359 1360
    # 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.")
1361

1362
    # test if a user (ASSIGNOR) can expire them
1363
    self.login('webmaster')
1364 1365 1366 1367 1368
    try:
      section_2.expire()
      section_6.expire()
    except Unauthorized:
      self.fail("An user should be able to expire a Web Section.")
1369

1370
  def test_05_createWebSite(self, quiet=quiet, run=run_all_test):
1371
    """ Test to create or clone web sites with many users """
1372 1373 1374 1375
    if not run: return
    if not quiet:
      message = '\ntest_05_createWebSite'
      ZopeTestCase._print(message)
1376

1377
    self.login('admin')
1378 1379 1380 1381 1382 1383 1384 1385 1386
    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)
1387
    self.login('webmaster')
1388 1389 1390 1391 1392
    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.")

1393 1394 1395 1396 1397
    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')

1398
  def test_06_createWebSection(self, quiet=quiet, run=run_all_test):
1399
    """ Test to create or clone web sections with many users """
1400 1401
    if not run: return
    if not quiet:
1402
      message = '\ntest_06_createWebSection'
1403
      ZopeTestCase._print(message)
1404

1405
    self.login('admin')
1406 1407
    web_site_module = self.portal.web_site_module
    site = web_site_module.newContent(portal_type='Web Site', id='site')
1408

1409 1410 1411 1412 1413 1414 1415
    # 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.")

1416
    # test as a webmaster (assignor)
1417
    self.login('webmaster')
1418 1419 1420 1421
    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:
1422
      self.fail("A webmaster should be able to create a Web Section.")
1423 1424 1425 1426 1427 1428 1429 1430
    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')
1431

1432 1433 1434 1435 1436 1437
  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)
1438

1439
    self.login('admin')
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    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)
1463
    self.login('webmaster')
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    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')
1490

1491 1492 1493 1494 1495 1496
  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)
1497

1498
    self.login('admin')
1499 1500
    portal_categories = self.portal.portal_categories
    publication_section = portal_categories.publication_section
1501

1502 1503 1504 1505 1506 1507 1508 1509
    # 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',
1510
      id='new_category_2')
1511 1512
    except Unauthorized:
      self.fail("Admin should be able to create a Category.")
1513
    transaction.commit()
1514 1515
    self.tic()
    try:
1516
      new_cat_1_renamed = new_category_1.edit(id='new_cat_1_renamed')
1517 1518 1519 1520
      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)
1521
    self.login('webmaster')
1522 1523 1524 1525 1526 1527 1528 1529 1530
    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',
1531
          id='new_category_4')
1532 1533
    except Unauthorized:
      self.fail("A webmaster should be able to create a Category.")
1534
    transaction.commit()
1535 1536
    self.tic()
    try:
1537
      new_cat_3_renamed = new_category_3.edit(id='new_cat_3_renamed')
1538 1539 1540
      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.")
1541

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
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())

1572 1573 1574
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Web))
1575
  suite.addTest(unittest.makeSuite(TestERP5WebWithSimpleSecurity))
1576
  suite.addTest(unittest.makeSuite(TestERP5WebCategoryPublicationWorkflow))
1577
  return suite