testERP5Web.py 79.2 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
import transaction
34
from AccessControl import Unauthorized
35
from Testing import ZopeTestCase
36
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
37
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
38
from Products.ERP5Type.tests.utils import DummyLocalizer
39
from Products.ERP5Type.tests.utils import createZODBPythonScript
40
from Products.ERP5Type.tests.backportUnittest import expectedFailure
41

Rafael Monnerat's avatar
Rafael Monnerat committed
42
LANGUAGE_LIST = ('en', 'fr', 'de', 'bg', )
43 44
HTTP_OK = 200
MOVED_TEMPORARILY = 302
45

Rafael Monnerat's avatar
Rafael Monnerat committed
46

47
class TestERP5Web(ERP5TypeTestCase):
48 49 50 51
  """Test for erp5_web business template.
  """
  manager_username = 'zope'
  manager_password = 'zope'
52
  website_id = 'test'
53
  credential = '%s:%s' % (manager_username, manager_password)
Rafael Monnerat's avatar
Rafael Monnerat committed
54

55 56 57 58 59 60 61
  def getTitle(self):
    return "ERP5Web"

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

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

    uf = portal.acl_users
Rafael Monnerat's avatar
Rafael Monnerat committed
72 73 74
    uf._doAddUser(self.manager_username,
                  self.manager_password,
                  ['Manager'], [])
75 76
    self.login(self.manager_username)

77 78
    self.web_page_module = self.portal.getDefaultModule('Web Page Module')
    self.web_site_module = self.portal.getDefaultModule('Web Site Module')
Rafael Monnerat's avatar
Rafael Monnerat committed
79
    portal.Localizer.manage_changeDefaultLang(language='en')
80 81
    self.portal_id = self.portal.getId()

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

87
  def beforeTearDown(self):
88 89
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
90
    self.clearModule(self.portal.person_module)
91

92
  def setupWebSite(self, **kw):
93
    """
94 95 96
      Setup Web Site
    """
    portal = self.getPortal()
97

98 99 100
    # add supported languages for Localizer
    localizer = portal.Localizer
    for language in LANGUAGE_LIST:
Rafael Monnerat's avatar
Rafael Monnerat committed
101
      localizer.manage_addLanguage(language=language)
102

103 104 105
    # create website
    if hasattr(self.web_site_module, self.website_id):
      self.web_site_module.manage_delObjects(self.website_id)
Rafael Monnerat's avatar
Rafael Monnerat committed
106 107 108
    website = self.web_site_module.newContent(portal_type='Web Site',
                                              id=self.website_id,
                                              **kw)
109
    website.publish()
110
    self.stepTic()
111
    return website
112

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

129
    self.stepTic()
130 131
    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
    """
      Setup some Web Pages.
    """
    webpage_list = []
    # create sample web pages
    for language in language_list:
      if suffix is not None:
141
        reference = '%s-%s' % (prefix, language)
142 143
      else:
        reference = prefix
144
      webpage = self.web_page_module.newContent(portal_type='Web Page',
145 146 147 148
                                                reference=reference,
                                                version=version,
                                                language=language,
                                                **kw)
149
      webpage.publish()
150
      self.stepTic()
151 152 153 154 155
      self.assertEquals(language, webpage.getLanguage())
      self.assertEquals(reference, webpage.getReference())
      self.assertEquals(version, webpage.getVersion())
      self.assertEquals('published', webpage.getValidationState())
      webpage_list.append(webpage)
156

157
    return webpage_list
158

159
  def test_01_WebSiteRecatalog(self):
160 161 162 163
    """
      Test that a recataloging works for Web Site documents
    """
    self.setupWebSite()
Rafael Monnerat's avatar
Rafael Monnerat committed
164
    web_site = self.web_site_module[self.website_id]
165

166 167 168 169 170 171 172 173
    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.')

174
  def test_02_EditSimpleWebPage(self):
175 176
    """
      Simple Case of creating a web page.
177 178 179
    """
    page = self.web_page_module.newContent(portal_type='Web Page')
    page.edit(text_content='<b>OK</b>')
180
    self.assertEquals('text/html', page.getContentType())
181
    self.assertEquals('<b>OK</b>', page.getTextContent())
182

183
  def test_02a_WebPageAsText(self):
184 185 186 187 188
    """
      Check if Web Page's asText() returns utf-8 string correctly and
      if it is wrapped by certian column width.
    """
    # disable portal_transforms cache
Rafael Monnerat's avatar
Rafael Monnerat committed
189
    self.portal.portal_transforms.max_sec_in_cache = -1
190 191
    page = self.web_page_module.newContent(portal_type='Web Page')
    page.edit(text_content='<p>Hé Hé Hé!</p>')
192
    self.stepTic()
193 194
    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>')
195
    self.stepTic()
196 197 198
    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())

199
  def test_03_CreateWebSiteUser(self):
200 201 202
    """
      Create Web site User.
    """
203
    self.setupWebSite()
204 205
    portal = self.getPortal()
    request = self.app.REQUEST
Rafael Monnerat's avatar
Rafael Monnerat committed
206 207 208 209 210 211
    kw = dict(reference='web',
              first_name='TestFN',
              last_name='TestLN',
              default_email_text='test@test.com',
              password='abc',
              password_confirm='abc',)
212
    for key, item in kw.items():
Rafael Monnerat's avatar
Rafael Monnerat committed
213 214
      request.set('field_your_%s' % key, item)
    website = self.web_site_module[self.website_id]
215
    website.WebSite_createWebSiteAccount('WebSite_viewRegistrationDialog')
216

217
    self.stepTic()
218

219
    # find person object by reference
Rafael Monnerat's avatar
Rafael Monnerat committed
220 221
    person = website.ERP5Site_getAuthenticatedMemberPersonValue(
                                                           kw['reference'])
222 223 224 225 226 227
    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')

228
    # check if user account is 'loggable'
229
    uf = portal.acl_users
Rafael Monnerat's avatar
Rafael Monnerat committed
230 231
    user = uf.getUserById(kw['reference'])
    self.assertEquals(str(user), kw['reference'])
232
    self.assertEquals(1, user.has_role(('Member', 'Authenticated',)))
233
    self.login(kw['reference'])
Rafael Monnerat's avatar
Rafael Monnerat committed
234 235
    self.assertEquals(kw['reference'],
                      str(portal.portal_membership.getAuthenticatedMember()))
236 237 238

    # test redirection to person oobject
    path = website.absolute_url_path() + '/WebSite_redirectToUserView'
Rafael Monnerat's avatar
Rafael Monnerat committed
239
    response = self.publish(path, '%s:%s' % (kw['reference'], kw['password']))
240
    self.assertTrue(person.getRelativeUrl() in response.getHeader("Location"))
Rafael Monnerat's avatar
Rafael Monnerat committed
241

242 243
    # test redirecting to new Person preference
    path = website.absolute_url_path() + '/WebSite_redirectToUserPreference'
Rafael Monnerat's avatar
Rafael Monnerat committed
244
    response = self.publish(path, '%s:%s' % (kw['reference'], kw['password']))
245 246
    self.assertTrue('portal_preferences' in response.getHeader("Location"))
    # one preference should be created for user
Rafael Monnerat's avatar
Rafael Monnerat committed
247 248 249
    self.assertEquals(1,
        self.portal.portal_catalog.countResults(**{'portal_type': 'Preference',
                                              'owner': kw['reference']})[0][0])
250

251
  def test_04_WebPageTranslation(self):
252
    """
253
      Simple Case of showing the proper Web Page based on
254 255 256 257 258 259
      current user selected language in browser.
    """
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
    page_reference = 'default-webpage'
Rafael Monnerat's avatar
Rafael Monnerat committed
260
    webpage_list = self.setupWebSitePages(prefix=page_reference)
261

262
    # set default web page for section
Rafael Monnerat's avatar
Rafael Monnerat committed
263 264 265 266 267
    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()],
268 269 270 271
                      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()))
272

273
    # use already created few pages in different languages with same reference
274
    # and check that we always get the right one based on selected
275 276 277
    # by us language
    for language in LANGUAGE_LIST:
      # set default language in Localizer only to check that we get
278
      # the corresponding web page for language.
279
      # XXX: Extend API so we can select language from REQUEST
Rafael Monnerat's avatar
Rafael Monnerat committed
280
      portal.Localizer.manage_changeDefaultLang(language=language)
281 282
      default_document = websection.getDefaultDocumentValue()
      self.assertEquals(language, default_document.getLanguage())
283

284
  def test_05_WebPageTextContentSubstitutions(self):
285
    """
Rafael Monnerat's avatar
Rafael Monnerat committed
286 287
      Simple Case of showing the proper text content with and without a
      substitution mapping method.
288
      In case of asText, the content should be replaced too
289 290
    """
    content = '<a href="${toto}">$titi</a>'
291
    asText_content = '$titi\n'
292
    substituted_content = '<a href="foo">bar</a>'
293
    substituted_asText_content = 'bar\n'
294 295 296
    mapping = dict(toto='foo', titi='bar')

    portal = self.getPortal()
297
    document = portal.web_page_module.newContent(portal_type='Web Page',
298
            text_content=content)
299

300 301
    # No substitution should occur.
    self.assertEquals(document.asStrippedHTML(), content)
302
    self.assertEquals(document.asText(), asText_content)
303 304 305 306 307 308 309

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

    # Substitutions should occur.
    self.assertEquals(document.asStrippedHTML(), substituted_content)
310
    self.assertEquals(document.asText(), substituted_asText_content)
311 312 313 314

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

Rafael Monnerat's avatar
Rafael Monnerat committed
315 316
    # Even with the same callable object, a restricted method
    # id should not be callable.
317 318
    self.assertRaises(Unauthorized, document.asStrippedHTML)

319
  def test_06_DefaultDocumentForWebSection(self):
320 321 322 323
    """
      Testing the default document for a Web Section.

      If a Web Section has a default document defined and if that default
324 325
      document is published, then getDefaultDocumentValue on that
      web section should return the latest version in the most
326
      appropriate language of that default document.
327 328

      Note: due to generic ERP5 Web implementation this test highly depends
329
      on WebSection_geDefaulttDocumentValueList
Ivan Tyagov's avatar
Ivan Tyagov committed
330 331 332
    """
    website = self.setupWebSite()
    websection = self.setupWebSection()
Rafael Monnerat's avatar
Rafael Monnerat committed
333
    publication_section_category_id_list = ['documentation', 'administration']
334

Ivan Tyagov's avatar
Ivan Tyagov committed
335
    # create pages belonging to this publication_section 'documentation'
Rafael Monnerat's avatar
Rafael Monnerat committed
336 337 338 339 340 341
    web_page_en = self.web_page_module.newContent(
             portal_type='Web Page',
             id='section_home',
             language='en',
             reference='NXD-DDP',
             publication_section_list=publication_section_category_id_list[:1])
Ivan Tyagov's avatar
Ivan Tyagov committed
342
    websection.setAggregateValue(web_page_en)
343
    self.stepTic()
344
    self.assertEqual(None, websection.getDefaultDocumentValue())
Ivan Tyagov's avatar
Ivan Tyagov committed
345 346
    # publish it
    web_page_en.publish()
347
    self.stepTic()
348 349 350 351 352 353 354
    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]
Rafael Monnerat's avatar
Rafael Monnerat committed
355 356
    self.assertEqual(base_url, "%s/%s/" % (websection.absolute_url(),
                                           web_page_en.getReference()))
357

358
  def test_06b_DefaultDocumentForWebSite(self):
359 360 361 362
    """
      Testing the default document for a Web Site.

      If a Web Section has a default document defined and if that default
363 364
      document is published, then getDefaultDocumentValue on that
      web section should return the latest version in the most
365
      appropriate language of that default document.
366 367

      Note: due to generic ERP5 Web implementation this test highly depends
368 369 370
      on WebSection_geDefaulttDocumentValueList
    """
    website = self.setupWebSite()
Rafael Monnerat's avatar
Rafael Monnerat committed
371
    publication_section_category_id_list = ['documentation', 'administration']
372

373
    # create pages belonging to this publication_section 'documentation'
Rafael Monnerat's avatar
Rafael Monnerat committed
374
    web_page_en = self.web_page_module.newContent(portal_type = 'Web Page',
375
                                                 id='site_home',
376 377 378
                                                 language = 'en',
                                                 reference='NXD-DDP-Site',
                                                 publication_section_list=publication_section_category_id_list[:1])
379
    website.setAggregateValue(web_page_en)
380
    self.stepTic()
381 382 383
    self.assertEqual(None, website.getDefaultDocumentValue())
    # publish it
    web_page_en.publish()
384
    self.stepTic()
385 386 387 388 389 390 391
    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]
392
    self.assertEqual(base_url, "%s/%s/" % (website.absolute_url(), web_page_en.getReference()))
393

394
  def test_07_WebSection_getDocumentValueList(self):
395 396 397 398 399
    """ Check getting getDocumentValueList from Web Section.
    """
    portal = self.getPortal()
    website = self.setupWebSite()
    websection = self.setupWebSection()
Rafael Monnerat's avatar
Rafael Monnerat committed
400
    publication_section_category_id_list = ['documentation', 'administration']
401

402
    #set predicate on web section using 'publication_section'
403
    websection.edit(membership_criterion_base_category = ['publication_section'],
404 405
                     membership_criterion_category=['publication_section/%s' \
                                                    % publication_section_category_id_list[0]])
406 407 408
    # clean up
    self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
    portal.portal_categories.publication_section.manage_delObjects(
409
                                      list(portal.portal_categories.publication_section.objectIds()))
410 411
    # create categories
    for category_id in publication_section_category_id_list:
412
      portal.portal_categories.publication_section.newContent(portal_type = 'Category',
413 414
                                                              id = category_id)

Rafael Monnerat's avatar
Rafael Monnerat committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    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"),
                     '14': dict(language='ja', version="2", reference="E"),
                     '15': dict(language='pt', version="2", reference="F"),
                     '16': dict(language='', version="1", reference="A"),
431 432
                    }
    sequence_one = property_dict.keys()
Rafael Monnerat's avatar
Rafael Monnerat committed
433 434 435 436
    sequence_two = ['01', '13', '12', '09', '06', '15', '04', '11', '02',
                    '05', '03', '07', '10', '08', '14', '16']
    sequence_three = ['05', '12', '13', '14', '06', '09', '10', '07',
                      '03', '01', '02', '11', '04', '08', '15', '16']
437

438
    sequence_count = 0
Rafael Monnerat's avatar
Rafael Monnerat committed
439
    for sequence in [sequence_one, sequence_two, sequence_three]:
440
      sequence_count += 1
441 442 443
      message = '\ntest_07_WebSection_getDocumentValueList (Sequence %s)' \
                                                              % (sequence_count)
      ZopeTestCase._print(message)
444

445
      web_page_list = []
446
      for key in sequence:
Rafael Monnerat's avatar
Rafael Monnerat committed
447
        web_page = self.web_page_module.newContent(
448
                                  title=key,
449 450
                                  portal_type = 'Web Page',
                                  publication_section_list=publication_section_category_id_list[:1])
451

452
        web_page.edit(**property_dict[key])
453
        self.stepTic()
454
        web_page_list.append(web_page)
455

456
      self.stepTic()
457
      # in draft state, no documents should belong to this Web Section
458
      self.assertEqual(0, len(websection.getDocumentValueList()))
459

460
      # when published, all web pages should belong to it
461 462
      for web_page in web_page_list:
        web_page.publish()
463
      self.stepTic()
464

465
      # Test for limit parameter
466
      self.assertEqual(2, len(websection.getDocumentValueList(limit=2)))
467 468

      # Testing for language parameter
469
      self.assertEqual(4, len(websection.getDocumentValueList()))
Rafael Monnerat's avatar
Rafael Monnerat committed
470 471
      self.assertEqual(['en', 'en', 'en', 'en'],
                       [w.getLanguage() for w in websection.getDocumentValueList()])
472

473 474 475 476 477
      # Check that receiving an empty string as language parameter (as done
      # when using listbox search) correctly returns user language documents.
      default_document_value_list = websection.getDocumentValueList(language='')
      self.assertEqual(4, len(default_document_value_list))
      self.assertEqual(['en', 'en', 'en', 'en'],
Rafael Monnerat's avatar
Rafael Monnerat committed
478
                       [w.getLanguage() for w in default_document_value_list])
479

480
      pt_document_value_list = websection.getDocumentValueList(language='pt')
481
      self.assertEqual(4, len(pt_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
482 483
      self.assertEqual(['pt', 'pt', 'pt', 'pt'],
                           [w.getObject().getLanguage() for w in pt_document_value_list])
484

485
      ja_document_value_list = websection.getDocumentValueList(language='ja')
486
      self.assertEqual(4, len(ja_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
487 488
      self.assertEqual(['ja', 'ja', 'ja', 'ja'],
                           [w.getLanguage() for w in ja_document_value_list])
489

490 491 492
      bg_document_value_list = websection.getDocumentValueList(language='bg')
      self.assertEqual(1, len(bg_document_value_list))
      self.assertEqual([''],
Rafael Monnerat's avatar
Rafael Monnerat committed
493
                       [w.getLanguage() for w in bg_document_value_list])
494

495 496 497
      # Testing for all_versions parameter
      en_document_value_list = websection.getDocumentValueList(all_versions=1)
      self.assertEqual(5, len(en_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
498 499
      self.assertEqual(['en', 'en', 'en', 'en', 'en'],
                       [w.getLanguage() for w in en_document_value_list])
500 501 502 503

      pt_document_value_list = websection.getDocumentValueList(language='pt',
                                                               all_versions=1)
      self.assertEqual(5, len(pt_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
504 505
      self.assertEqual(['pt', 'pt', 'pt', 'pt', 'pt'],
                       [w.getObject().getLanguage() for w in pt_document_value_list])
506

507
      ja_document_value_list = websection.getDocumentValueList(language='ja',
508 509
                                                               all_versions=1)
      self.assertEqual(5, len(ja_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
510 511
      self.assertEqual(['ja', 'ja', 'ja', 'ja', 'ja'],
                           [w.getLanguage() for w in ja_document_value_list])
512 513

      # Tests for all_languages parameter
514 515
      en_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1)
      self.assertEqual(6, len(en_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
516
      self.assertEqual(4, len([w.getLanguage() for w in en_document_value_list \
517
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
518
      self.assertEqual(1, len([w.getLanguage() for w in en_document_value_list \
519
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
520
      self.assertEqual(['3'], [w.getVersion() for w in en_document_value_list \
521
                              if w.getLanguage() == 'pt'])
Rafael Monnerat's avatar
Rafael Monnerat committed
522
      self.assertEqual(1, len([w.getLanguage() for w in en_document_value_list \
523
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
524
      self.assertEqual(['3'], [w.getVersion() for w in en_document_value_list \
525
                              if w.getLanguage() == 'ja'])
526

527 528 529
      pt_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              language='pt')
      self.assertEqual(6, len(pt_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
530
      self.assertEqual(4, len([w.getLanguage() for w in pt_document_value_list \
531
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
532
      self.assertEqual(1, len([w.getLanguage() for w in pt_document_value_list \
533
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
534
      self.assertEqual(['3'], [w.getVersion() for w in pt_document_value_list \
535
                              if w.getLanguage() == 'en'])
Rafael Monnerat's avatar
Rafael Monnerat committed
536
      self.assertEqual(1, len([w.getLanguage() for w in pt_document_value_list \
537
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
538
      self.assertEqual(['3'], [w.getVersion() for w in pt_document_value_list \
539
                              if w.getLanguage() == 'ja'])
540

541 542 543
      ja_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              language='ja')
      self.assertEqual(6, len(ja_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
544
      self.assertEqual(4, len([w.getLanguage() for w in ja_document_value_list \
545
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
546
      self.assertEqual(1, len([w.getLanguage() for w in ja_document_value_list \
547
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
548
      self.assertEqual(['3'], [w.getVersion() for w in ja_document_value_list \
549
                              if w.getLanguage() == 'pt'])
Rafael Monnerat's avatar
Rafael Monnerat committed
550
      self.assertEqual(1, len([w.getLanguage() for w in ja_document_value_list \
551
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
552
      self.assertEqual(['3'], [w.getVersion() for w in ja_document_value_list \
553 554
                            if w.getLanguage() == 'en'])

555 556 557
      bg_document_value_list = websection.WebSection_getDocumentValueListBase(all_languages=1,
                                                                              language='bg')
      self.assertEqual(6, len(bg_document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
558
      self.assertEqual(0, len([w.getLanguage() for w in bg_document_value_list \
559
                              if w.getLanguage() == 'bg']))
Rafael Monnerat's avatar
Rafael Monnerat committed
560
      self.assertEqual(3, len([w.getLanguage() for w in bg_document_value_list \
561
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
562
      self.assertEqual(1, len([w.getLanguage() for w in bg_document_value_list \
563
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
564
      self.assertEqual(['3'], [w.getVersion() for w in bg_document_value_list \
565
                              if w.getLanguage() == 'pt'])
Rafael Monnerat's avatar
Rafael Monnerat committed
566
      self.assertEqual(1, len([w.getLanguage() for w in bg_document_value_list \
567
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
568
      self.assertEqual(['3'], [w.getVersion() for w in bg_document_value_list \
569 570
                            if w.getLanguage() == 'ja'])

571
      # Tests for all_languages and all_versions
572 573 574 575 576 577 578 579 580 581 582
      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')

Rafael Monnerat's avatar
Rafael Monnerat committed
583
      for document_value_list in [en_document_value_list, pt_document_value_list,
584 585
                                   ja_document_value_list]:

586
        self.assertEqual(16, len(document_value_list))
Rafael Monnerat's avatar
Rafael Monnerat committed
587
        self.assertEqual(5, len([w.getLanguage() for w in document_value_list \
588
                                if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
589
        self.assertEqual(5, len([w.getLanguage() for w in en_document_value_list \
590
                                if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
591
        self.assertEqual(5, len([w.getLanguage() for w in en_document_value_list \
592 593 594
                                if w.getLanguage() == 'ja']))

      # Tests for sort_on parameter
Rafael Monnerat's avatar
Rafael Monnerat committed
595 596
      self.assertEqual(['A', 'B', 'C', 'D'],
                       [w.getReference() for w in \
597 598
                         websection.getDocumentValueList(sort_on=[('reference', 'ASC')])])

Rafael Monnerat's avatar
Rafael Monnerat committed
599 600
      self.assertEqual(['01', '02', '03', '13'],
                       [w.getTitle() for w in \
601 602
                         websection.getDocumentValueList(sort_on=[('title', 'ASC')])])

Rafael Monnerat's avatar
Rafael Monnerat committed
603 604
      self.assertEqual(['D', 'C', 'B', 'A'],
                       [w.getReference() for w in \
605 606
                         websection.getDocumentValueList(sort_on=[('reference', 'DESC')])])

Rafael Monnerat's avatar
Rafael Monnerat committed
607 608
      self.assertEqual(['13', '03', '02', '01'],
                       [w.getTitle() for w in \
609 610
                         websection.getDocumentValueList(sort_on=[('reference', 'DESC')])])

Rafael Monnerat's avatar
Rafael Monnerat committed
611 612
      self.assertEqual(['A', 'B', 'C', 'D', 'E', 'F'],
                       [w.getReference() for w in \
613 614
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('reference', 'ASC')])])
615

Rafael Monnerat's avatar
Rafael Monnerat committed
616 617
      self.assertEqual(['01', '02', '03', '11', '12', '13'],
                       [w.getTitle() for w in \
618 619 620
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('title', 'ASC')])])

Rafael Monnerat's avatar
Rafael Monnerat committed
621 622
      self.assertEqual(['F', 'E', 'D', 'C', 'B', 'A'],
                       [w.getReference() for w in \
623 624 625
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('reference', 'DESC')])])

Rafael Monnerat's avatar
Rafael Monnerat committed
626 627
      self.assertEqual(['13', '12', '11', '03', '02', '01'],
                       [w.getTitle() for w in \
628 629 630
                         websection.WebSection_getDocumentValueListBase(all_languages=1,
                                            sort_on=[('title', 'DESC')])])

631
      self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
632

633
  def test_08_AcquisitionWrappers(self):
634 635 636 637 638 639 640 641 642 643 644 645
    """Test acquisition wrappers of documents.
    Check if documents obtained by getDefaultDocumentValue, getDocumentValue
    and getDocumentValueList are wrapped appropriately.
    """
    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')
646
      self.stepTic()
647 648 649 650 651 652

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

654 655 656 657 658 659 660 661 662 663 664
    # 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])
665
    self.stepTic()
666

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    # 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)
684

685
  def test_09_WebSiteSkinSelection(self):
686 687 688 689 690 691 692 693 694
    """Test skin selection through a Web Site.
    Check if a Web Site can change a skin selection based on a property.
    """
    portal = self.getPortal()
    ps = portal.portal_skins
    website = self.setupWebSite()

    # First, make sure that we use the default skin selection.
    portal.changeSkin(ps.getDefaultSkin())
695
    self.stepTic()
696 697 698 699 700 701 702 703 704 705

    # 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',))
706

707 708 709 710 711 712 713 714 715 716 717 718 719
    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"')

720
    self.stepTic()
721 722 723 724 725 726 727 728 729 730

    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')
731
    self.stepTic()
732 733 734 735

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

736
  def test_10_getDocumentValueList(self):
737 738 739 740 741 742 743
    """Make sure that getDocumentValueList works."""
    self.setupWebSite()
    website = self.web_site_module[self.website_id]
    website.getDocumentValueList(
      portal_type='Document',
      sort_on=[('translated_portal_type', 'ascending')])

744
  def test_11_getWebSectionValueList(self):
745 746 747 748 749 750 751 752 753
    """ Check getWebSectionValueList from Web Site.
    Only visible web section should be returned.
    """
    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
Rafael Monnerat's avatar
Rafael Monnerat committed
754
    web_site = self.web_site_module.newContent(portal_type=web_site_portal_type)
755 756 757 758
    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
Rafael Monnerat's avatar
Rafael Monnerat committed
759
    web_page = self.web_page_module.newContent(portal_type=web_page_portal_type)
760 761 762 763

    # Commit transaction
    def _commit():
      portal.portal_caches.clearAllCache()
764
      self.stepTic()
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

    # 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()
780
    self.assertSameSet([web_section],
781 782 783 784 785 786 787
                       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()
788
    self.assertSameSet([sub_web_section],
789 790
                       web_site.getWebSectionValueList(web_page))

Romain Courteaud's avatar
Romain Courteaud committed
791 792
    # Set leaf web section visible, which should be returned even if parent is
    # not visible
793 794 795
    web_section.setVisible(0)
    sub_web_section.setVisible(1)
    _commit()
796
    self.assertSameSet([sub_web_section],
797 798
                       web_site.getWebSectionValueList(web_page))

799
  def test_12_getWebSiteValue(self):
800
    """
801 802
      Test that getWebSiteValue() and getWebSectionValue() always
      include selected Language.
803
    """
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
    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'
822 823 824 825
    page = self.web_page_module.newContent(portal_type='Web Page',
                                           reference='foo',
                                           text_content='<b>OK</b>')
    page.publish()
826
    self.stepTic()
827

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    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))
873

874
  def test_13_DocumentCache(self):
875
    """
876
      Test that when a document is modified, it can be accessed through a
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
      web_site, a web_section or wathever and display the last content (not an
      old cache value of the document).
    """
    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
    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()
894
    self.stepTic()
895 896
    self.assertEquals(document.asText().strip(), 'initial text')

897 898 899 900 901 902 903
    # First make sure conversion already exists on the web site
    web_document = website.restrictedTraverse('NXD-Document.Cache')
    self.assertTrue(web_document.hasConversion(format='txt'))
    web_document = web_section.restrictedTraverse('NXD-Document.Cache')
    self.assertTrue(web_document.hasConversion(format='txt'))

    # Through the web_site.
904
    path = website.absolute_url_path() + '/NXD-Document.Cache'
905
    response = self.publish(path, self.credential)
906
    self.assertNotEquals(response.getBody().find(content), -1)
907

908
    # Through a web_section.
909
    path = web_section.absolute_url_path() + '/NXD-Document.Cache'
910
    response = self.publish(path, self.credential)
911
    self.assertNotEquals(response.getBody().find(content), -1)
912 913 914 915

    # modified the web_page content
    document.edit(text_content=new_content)
    self.assertEquals(document.asText().strip(), 'modified text')
916
    self.stepTic()
917

918 919
    # check the cache doesn't send again the old content
    # Through the web_site.
920
    path = website.absolute_url_path() + '/NXD-Document.Cache'
921 922
    response = self.publish(path, self.credential)
    self.assertNotEquals(response.getBody().find(new_content), -1)
923

924
    # Through a web_section.
925
    path = web_section.absolute_url_path() + '/NXD-Document.Cache'
926 927
    response = self.publish(path, self.credential)
    self.assertNotEquals(response.getBody().find(new_content), -1)
928

929
  def test_13a_DocumentMovedCache(self):
930
    """
931
      What happens to the cache if document is moved
932
      with a new ID. Can we still access content,
933
      or is the cache emptied. There is no reason
934
      that the cache should be regenerated or that the
935
      previous cache would not be emptied.
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

      Here, we test that the cache is not regenerated,
      not emptied, and still available.
    """
    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
    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_original_cache',
            reference='NXD-Document.Cache',
            text_content=content)
    document.publish()
954
    self.stepTic()
955 956 957 958
    self.assertEquals(document.asText().strip(), 'initial text')

    # Make sure document cache keeps converted content even if ID changes
    self.assertTrue(document.hasConversion(format='txt'))
959
    document.setId('document_new_cache')
960
    self.assertTrue(document.hasConversion(format='txt'))
961
    document.setId('document_original_cache')
962 963
    self.assertTrue(document.hasConversion(format='txt'))

964
  def test_13b_DocumentEditCacheKey(self):
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
    """
      What happens if a web page is edited on a web site ?
      Is converted content cleared and updated ? Or
      is a wrong cache key created ? Here, we make sure
      that the content is updated and the cache cleared
      and reset.
    """
    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
    website = self.setupWebSite()
    web_section_portal_type = 'Web Section'
    web_section = website.newContent(portal_type=web_section_portal_type)

    content = '<p>initial text</p>'
980
    new_content = '<p>modified text</p>'
981 982 983 984 985
    document = portal.web_page_module.newContent(portal_type='Web Page',
            id='document_cache',
            reference='NXD-Document.Cache',
            text_content=content)
    document.publish()
986
    self.stepTic()
987 988 989 990
    self.assertEquals(document.asText().strip(), 'initial text')

    # Through the web_site.
    path = website.absolute_url_path() + '/NXD-Document.Cache'
991
    response = self.publish(path, self.credential)
992
    self.assertNotEquals(response.getBody().find(content), -1)
993 994
    # Through a web_section.
    path = web_section.absolute_url_path() + '/NXD-Document.Cache'
995
    response = self.publish(path, self.credential)
996
    self.assertNotEquals(response.getBody().find(content), -1)
997 998 999

    # Modify the web_page content
    # Use unrestrictedTraverse (XXX-JPS reason unknown)
1000
    web_document = website.unrestrictedTraverse('web_page_module/%s' % document.getId())
1001 1002 1003 1004 1005 1006
    web_document.edit(text_content=new_content)
    # Make sure cached is emptied
    self.assertFalse(web_document.hasConversion(format='txt'))
    self.assertFalse(document.hasConversion(format='txt'))
    # Make sure cache is regenerated
    self.assertEquals(web_document.asText().strip(), 'modified text')
1007
    self.stepTic()
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

    # First make sure conversion already exists (since it should
    # have been generated previously)
    self.assertTrue(document.hasConversion(format='txt'))
    web_document = web_section.restrictedTraverse('NXD-Document.Cache')
    self.assertTrue(web_document.hasConversion(format='txt'))
    web_document = website.restrictedTraverse('NXD-Document.Cache')
    self.assertTrue(web_document.hasConversion(format='txt'))

    # check the cache doesn't send again the old content
    # test this fist on the initial document
    self.assertEquals(document.asText().strip(), 'modified text')

    # Through a web_section.
    web_document = web_section.restrictedTraverse('NXD-Document.Cache')
    self.assertEquals(web_document.asText().strip(), 'modified text')
    path = web_section.absolute_url_path() + '/NXD-Document.Cache'
1025
    response = self.publish(path, self.credential)
1026
    self.assertNotEquals(response.getBody().find(new_content), -1)
1027 1028 1029 1030 1031

    # Through a web_site.
    web_document = website.restrictedTraverse('NXD-Document.Cache')
    self.assertEquals(web_document.asText().strip(), 'modified text')
    path = website.absolute_url_path() + '/NXD-Document.Cache'
1032
    response = self.publish(path, self.credential)
1033
    self.assertNotEquals(response.getBody().find(new_content), -1)
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, {})
1054
    self.stepTic()
1055 1056 1057
    preference_tool = self.getPreferenceTool()
    isTransitionPossible = self.portal.portal_workflow.isTransitionPossible

1058
    # create or edit preference for administrator
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    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)

1072
    # create or edit preference for webeditor
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    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()
1086
    self.stepTic()
1087 1088 1089 1090 1091 1092

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

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

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

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

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

1108
  def test_15_Check_LastModified_Header(self):
Nicolas Delaby's avatar
Nicolas Delaby committed
1109
    """Checks that Last-Modified header set by caching policy manager
1110
    is correctly filled with getModificationDate of content.
1111
    This test check 2 Policy installed by erp5_web:
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    Policy ID - unauthenticated web pages
                authenticated
    """
    website = self.setupWebSite()
    web_section_portal_type = 'Web Section'
    web_section = website.newContent(portal_type=web_section_portal_type)

    content = '<p>initial text</p>'
    document = self.portal.web_page_module.newContent(portal_type='Web Page',
            id='document_cache',
            reference='NXD-Document.Cache',
            text_content=content)
    document.publish()
1125
    self.stepTic()
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    path = website.absolute_url_path() + '/NXD-Document.Cache'
    # test Different Policy installed by erp5_web
    # unauthenticated web pages
    response = self.publish(path)
    last_modified_header = response.getHeader('Last-Modified')
    self.assertTrue(last_modified_header)
    from App.Common import rfc1123_date
    # Convert the Date into string according RFC 1123 Time Format
    modification_date = rfc1123_date(document.getModificationDate())
    self.assertEqual(modification_date, last_modified_header)

    # authenticated
    user = self.createUser('webmaster')
    self.createUserAssignement(user, {})
    response = self.publish(path, 'webmaster:webmaster')
    last_modified_header = response.getHeader('Last-Modified')
    self.assertTrue(last_modified_header)
    # Convert the Date into string according RFC 1123 Time Format
    modification_date = rfc1123_date(document.getModificationDate())
    self.assertEqual(modification_date, last_modified_header)
1146

1147
  def test_16_404ErrorPageIsReturned(self):
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    """
      Test that when we try to access a non existing url trought a web site, a
      404 error page is returned
    """
    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
    website = self.setupWebSite()
    path = website.absolute_url_path() + '/a_non_existing_page'
    absolute_url = website.absolute_url() + '/a_non_existing_page'
    request = portal.REQUEST

    # Check a Not Found page is returned
    self.assertTrue('Not Found' in request.traverse(path)())
    # Check that we try to display a page with 404.error.page reference
    self.assertEqual(request.traverse(path).absolute_url().split('/')[-1],
    '404.error.page')
1165

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
  @expectedFailure
  def test_17_WebSectionEditionWithLanguageInURL(self):
    """
    Check that editing a web section with the language in the URL
    does not prevent indexation.

    - Create a web site
    - Activate the language in the URL
    - Create a web section
    - Access it using another language and edit it
    - Check that web section is correctly indexed
    """
    language = 'de'

    website = self.setupWebSite()
    # Check that language in defined in the URL
    self.assertEquals(True, website.getStaticLanguageSelection())
    self.assertNotEquals(language, website.getDefaultAvailableLanguage())

    websection = self.setupWebSection()
    self.assertEquals(websection.getId(), websection.getTitle())

1188
    self.stepTic()
1189
    response = self.publish('/%s/%s/%s/%s/Base_editAndEditAsWeb' % \
Rafael Monnerat's avatar
Rafael Monnerat committed
1190
                    (self.portal.getId(), website.getRelativeUrl(),
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                     language, websection.getId()),
                     basic='ERP5TypeTestCase:',
                     request_method='POST',
                     extra={
                       'form_id': 'WebSection_view',
                       'form_action': 'Base_edit',
                       'edit_document_url': '%s/%s/%s/WebSection_view' % \
                           (website.absolute_url(), language,
                             websection.getId()),
                       'field_my_title': '%s_edited' % websection.getId(),
                     }
                    )
Rafael Monnerat's avatar
Rafael Monnerat committed
1203

1204 1205 1206 1207
    self.assertEquals(MOVED_TEMPORARILY, response.getStatus())
    new_location = response.getHeader('Location')
    new_location = new_location.split('/', 3)[-1]

1208
    self.stepTic()
1209 1210 1211

    response = self.publish(new_location, basic='ERP5TypeTestCase:',)
    self.assertEquals(HTTP_OK, response.getStatus())
Rafael Monnerat's avatar
Rafael Monnerat committed
1212
    self.assertEquals('text/html; charset=utf-8',
1213 1214 1215
                      response.getHeader('content-type'))
    self.assertTrue("Data updated." in response.getBody())

1216
    self.stepTic()
1217 1218 1219

    self.assertEquals('%s_edited' % websection.getId(), websection.getTitle())
    self.assertEquals(1, len(self.portal.portal_catalog(
Rafael Monnerat's avatar
Rafael Monnerat committed
1220
                                    relative_url=websection.getRelativeUrl(),
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
                                    title=websection.getTitle())))

  @expectedFailure
  def test_18_WebSiteEditionWithLanguageInURL(self):
    """
    Check that editing a web section with the language in the URL
    does not prevent indexation.

    - Create a web site
    - Activate the language in the URL
    - Access it using another language and edit it
    - Check that web site is correctly modified
    """
    language = 'de'

    website = self.setupWebSite()
    # Check that language in defined in the URL
    self.assertEquals(True, website.getStaticLanguageSelection())
    self.assertNotEquals(language, website.getDefaultAvailableLanguage())

    self.assertEquals(website.getId(), website.getTitle())

1243
    self.stepTic()
1244 1245

    response = self.publish('/%s/%s/%s/Base_editAndEditAsWeb' % \
Rafael Monnerat's avatar
Rafael Monnerat committed
1246
                    (self.portal.getId(), website.getRelativeUrl(),
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
                     language),
                     basic='ERP5TypeTestCase:',
                     request_method='POST',
                     extra={
                       'form_id': 'WebSite_view',
                       'form_action': 'Base_edit',
                       'edit_document_url': '%s/%s/WebSite_view' % \
                           (website.absolute_url(), language),
                       'field_my_title': '%s_edited' % website.getId(),
                       'field_my_id': language,
                     }
                    )
Rafael Monnerat's avatar
Rafael Monnerat committed
1259

1260 1261 1262 1263
    self.assertEquals(MOVED_TEMPORARILY, response.getStatus())
    new_location = response.getHeader('Location')
    new_location = new_location.split('/', 3)[-1]

1264
    self.stepTic()
1265 1266 1267

    response = self.publish(new_location, basic='ERP5TypeTestCase:',)
    self.assertEquals(HTTP_OK, response.getStatus())
Rafael Monnerat's avatar
Rafael Monnerat committed
1268
    self.assertEquals('text/html; charset=utf-8',
1269 1270 1271
                      response.getHeader('content-type'))
    self.assertTrue("Data updated." in response.getBody())

1272
    self.stepTic()
1273 1274 1275

    self.assertEquals('%s_edited' % website.getId(), website.getTitle())
    self.assertEquals(1, len(self.portal.portal_catalog(
Rafael Monnerat's avatar
Rafael Monnerat committed
1276
                                    relative_url=website.getRelativeUrl(),
1277 1278
                                    title=website.getTitle())))

1279 1280
  def test_19_WebModeAndEditableMode(self):
    """
Rafael Monnerat's avatar
Rafael Monnerat committed
1281
    Check if isWebMode & isEditableMode API works.
1282 1283 1284
    """
    request = self.app.REQUEST
    website = self.setupWebSite()
Rafael Monnerat's avatar
Rafael Monnerat committed
1285

1286 1287 1288 1289
    # web mode
    self.assertEquals(False, self.portal.person_module.isWebMode())
    self.assertEquals(True, website.isWebMode())
    self.assertEquals(True, getattr(website, 'person_module').isWebMode())
Rafael Monnerat's avatar
Rafael Monnerat committed
1290

1291 1292 1293 1294
    # editable mode
    self.assertEquals(False, self.portal.person_module.isEditableMode())
    self.assertEquals(False, website.isEditableMode())
    self.assertEquals(False, getattr(website, 'person_module').isEditableMode())
Rafael Monnerat's avatar
Rafael Monnerat committed
1295

1296 1297 1298 1299
    request.set('editable_mode', 1)
    self.assertEquals(1, self.portal.person_module.isEditableMode())
    self.assertEquals(1, website.isEditableMode())
    self.assertEquals(1, getattr(website, 'person_module').isEditableMode())
1300 1301 1302

  def test_20_reStructuredText(self):
    web_page = self.portal.web_page_module.newContent(portal_type='Web Page',
1303 1304
                                                      content_type='text/x-rst')
    web_page.edit(text_content="`foo`")
1305 1306 1307
    self.assertTrue('<cite>foo</cite>' in web_page.asEntireHTML(charset='utf-8'))
    self.assertTrue('<cite>foo</cite>' in web_page.asEntireHTML())

Ivan Tyagov's avatar
Ivan Tyagov committed
1308 1309 1310 1311 1312 1313
  def test_21_WebSiteMap(self):
    """
      Test Web Site map script.
    """
    request = self.app.REQUEST
    website = self.setupWebSite()
Rafael Monnerat's avatar
Rafael Monnerat committed
1314 1315 1316
    kw = {'depth': 5,
          'include_subsection': 1}

Ivan Tyagov's avatar
Ivan Tyagov committed
1317 1318
    website.setSiteMapSectionParent(1)
    websection1 = website.newContent(portal_type='Web Section',
Rafael Monnerat's avatar
Rafael Monnerat committed
1319 1320
                                     title='Section 1',
                                     site_map_section_parent=1,
Ivan Tyagov's avatar
Ivan Tyagov committed
1321 1322
                                     visible=1)
    websection1_1 = websection1.newContent(portal_type='Web Section',
Rafael Monnerat's avatar
Rafael Monnerat committed
1323 1324 1325
                                     title='Section 1.1',
                                     site_map_section_parent=1,
                                     visible=1)
Ivan Tyagov's avatar
Ivan Tyagov committed
1326
    self.stepTic()
Rafael Monnerat's avatar
Rafael Monnerat committed
1327 1328
    site_map = website.WebSection_getSiteMapTree(depth=5, include_subsection=1)
    self.assertSameSet([websection1.getTitle()],
Ivan Tyagov's avatar
Ivan Tyagov committed
1329
                       [x['translated_title'] for x in site_map])
Rafael Monnerat's avatar
Rafael Monnerat committed
1330
    self.assertSameSet([websection1_1.getTitle()],
Ivan Tyagov's avatar
Ivan Tyagov committed
1331
                       [x['translated_title'] for x in site_map[0]['subsection']])
Rafael Monnerat's avatar
Rafael Monnerat committed
1332 1333 1334
    self.assertEqual(1, site_map[0]['level'])
    self.assertEqual(2, site_map[0]['subsection'][0]['level'])

Ivan Tyagov's avatar
Ivan Tyagov committed
1335
    # check depth works
Rafael Monnerat's avatar
Rafael Monnerat committed
1336
    site_map = website.WebSection_getSiteMapTree(depth=1, include_subsection=1)
Ivan Tyagov's avatar
Ivan Tyagov committed
1337
    self.assertEqual(None, site_map[0]['subsection'])
Rafael Monnerat's avatar
Rafael Monnerat committed
1338
    self.assertSameSet([websection1.getTitle()],
Ivan Tyagov's avatar
Ivan Tyagov committed
1339
                       [x['translated_title'] for x in site_map])
Rafael Monnerat's avatar
Rafael Monnerat committed
1340

Ivan Tyagov's avatar
Ivan Tyagov committed
1341 1342
    # hide subsections
    websection1_1.setSiteMapSectionParent(0)
Rafael Monnerat's avatar
Rafael Monnerat committed
1343
    websection1_1.setVisible(0)
Ivan Tyagov's avatar
Ivan Tyagov committed
1344
    self.stepTic()
Rafael Monnerat's avatar
Rafael Monnerat committed
1345 1346
    site_map = website.WebSection_getSiteMapTree(depth=5, include_subsection=1)
    self.assertSameSet([websection1.getTitle()],
Ivan Tyagov's avatar
Ivan Tyagov committed
1347
                       [x['translated_title'] for x in site_map])
Rafael Monnerat's avatar
Rafael Monnerat committed
1348
    self.assertEqual(None, site_map[0]['subsection'])
Ivan Tyagov's avatar
Ivan Tyagov committed
1349

1350

1351 1352 1353 1354 1355 1356 1357
class TestERP5WebWithSimpleSecurity(ERP5TypeTestCase):
  """
  Test for erp5_web with simple security.
  """

  def getBusinessTemplateList(self):
    return ('erp5_base',
1358
            'erp5_pdm',
1359 1360
            'erp5_trade',
            'erp5_project',
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
            '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):
1372
    self.web_site_module = self.portal.web_site_module
1373 1374 1375
    self.portal.Localizer = DummyLocalizer()
    self.createUser('admin', ['Manager'])
    self.createUser('erp5user', ['Auditor', 'Author'])
1376
    self.createUser('webmaster', ['Assignor'])
1377
    transaction.commit()
1378 1379
    self.tic()

1380 1381
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
1382
    transaction.commit()
1383 1384
    self.tic()

1385
  def beforeTearDown(self):
1386 1387
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
1388

1389
  def test_01_AccessWebPageByReference(self):
1390
    self.login('admin')
1391 1392 1393 1394
    site = self.portal.web_site_module.newContent(portal_type='Web Site',
                                                  id='site')
    section = site.newContent(portal_type='Web Section', id='section')

1395
    transaction.commit()
1396 1397 1398 1399 1400
    self.tic()

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

1401
    transaction.commit()
1402 1403
    self.tic()

1404
    self.login('erp5user')
1405 1406 1407 1408 1409 1410 1411
    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!')

1412
    transaction.commit()
1413 1414 1415 1416
    self.tic()

    page_en.publish()

1417
    transaction.commit()
1418 1419 1420 1421 1422 1423 1424 1425 1426
    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='こんにちは、世界!')

1427
    transaction.commit()
1428 1429 1430 1431
    self.tic()

    page_ja.publish()

1432
    transaction.commit()
1433 1434 1435 1436 1437 1438 1439
    self.tic()

    # By Anonymous
    self.logout()

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

1440
    target = self.portal.unrestrictedTraverse('web_site_module/site/section/my-first-web-page')
1441 1442 1443 1444
    self.assertEqual('Hello, World!', target.getTextContent())

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

1445
    target = self.portal.unrestrictedTraverse('web_site_module/site/section/my-first-web-page')
1446
    self.assertEqual('こんにちは、世界!', target.getTextContent())
1447

1448
  def test_02_LocalRolesFromRoleDefinition(self):
1449 1450 1451 1452 1453 1454
    """ Test setting local roles on Web Site/ Web Sectio using ERP5 Role Definition objects . """
    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')
1455
    person = portal.person_module.newContent(portal_type = 'Person',
1456
                                             reference = person_reference)
1457
    # add Role Definition for site and section
1458 1459
    site_role_definition = site.newContent(portal_type = 'Role Definition',
                                           role_name = 'Assignee',
1460
                                           agent = person.getRelativeUrl())
1461 1462
    section_role_definition = section.newContent(portal_type = 'Role Definition',
                                                 role_name = 'Associate',
1463
                                                 agent = person.getRelativeUrl())
1464
    transaction.commit()
1465 1466
    self.tic()
    # check if Role Definition have create local roles
1467
    self.assertSameSet(('Assignee',),
1468
                          site.get_local_roles_for_userid(person_reference))
1469
    self.assertSameSet(('Associate',),
1470
                          section.get_local_roles_for_userid(person_reference))
1471 1472
    self.assertRaises(Unauthorized, site_role_definition.edit,
                      role_name='Manager')
1473

1474 1475 1476
    # 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())
1477
    transaction.commit()
1478
    self.tic()
1479
    self.assertSameSet((),
1480 1481 1482 1483
                       site.get_local_roles_for_userid(person_reference))
    self.assertSameSet((),
                       section.get_local_roles_for_userid(person_reference))

1484
  def test_03_WebSection_getDocumentValueListSecurity(self):
1485
    """ Test WebSection_getDocumentValueList behaviour and security"""
1486
    self.login('admin')
1487
    site = self.portal.web_site_module.newContent(portal_type='Web Site',
1488
                                      id='site')
1489
    site.publish()
1490

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

1494
    transaction.commit()
1495 1496 1497
    self.tic()

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

1501
    transaction.commit()
1502 1503
    self.tic()

1504
    self.login('erp5user')
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    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!')

1533
    transaction.commit()
1534
    self.login('erp5user')
1535 1536
    self.tic()
    self.portal.Localizer.changeLanguage('en')
1537

1538
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))
1539

1540
    self.login('erp5user')
1541
    page_en_0.publish()
1542
    transaction.commit()
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
    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()))
1557
    self.assertEquals(page_en_0.getUid(),
1558 1559 1560 1561 1562
                      section.WebSection_getDocumentValueList()[0].getUid())
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # Second Object
1563
    self.login('erp5user')
1564
    page_en_1.publish()
1565
    transaction.commit()
1566 1567 1568 1569
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
1570
    self.assertEquals(page_en_1.getUid(),
1571 1572 1573 1574 1575 1576 1577 1578
                      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()))
1579
    self.assertEquals(page_en_1.getUid(),
1580 1581 1582
                      section.WebSection_getDocumentValueList()[0].getUid())

    # Trird Object
1583
    self.login('erp5user')
1584
    page_en_2.publish()
1585
    transaction.commit()
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
    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()))

1600
    # First Japanese Object
1601
    self.login('erp5user')
1602
    page_jp_0.publish()
1603
    transaction.commit()
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    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()))
1617
    self.assertEquals(page_jp_0.getUid(),
1618
                      section.WebSection_getDocumentValueList()[0].getUid())
1619

1620
  def test_04_ExpireUserAction(self):
1621
    """ Test the expire user action"""
1622
    self.login('admin')
1623
    site = self.portal.web_site_module.newContent(portal_type='Web Site', id='site')
1624 1625 1626 1627 1628 1629 1630 1631

    # 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')
1632
    transaction.commit()
1633 1634
    self.tic()

1635 1636 1637 1638 1639 1640
    # 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.")
1641

1642
    # test if a user (ASSIGNOR) can expire them
1643
    self.login('webmaster')
1644 1645 1646 1647 1648
    try:
      section_2.expire()
      section_6.expire()
    except Unauthorized:
      self.fail("An user should be able to expire a Web Section.")
1649

1650
  def test_05_createWebSite(self):
1651
    """ Test to create or clone web sites with many users """
1652
    self.login('admin')
1653
    web_site_module = self.portal.web_site_module
1654 1655 1656 1657 1658 1659 1660 1661

    # 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)
1662
    self.login('webmaster')
1663 1664 1665 1666 1667
    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.")

1668 1669 1670 1671 1672
    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')

1673
  def test_06_createWebSection(self):
1674
    """ Test to create or clone web sections with many users """
1675
    self.login('admin')
1676
    site = self.portal.web_site_module.newContent(portal_type='Web Site', id='site')
1677

1678 1679 1680 1681 1682 1683 1684
    # 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.")

1685
    # test as a webmaster (assignor)
1686
    self.login('webmaster')
1687 1688 1689 1690
    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:
1691
      self.fail("A webmaster should be able to create a Web Section.")
1692 1693 1694 1695 1696 1697 1698 1699
    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')
1700

1701
  def test_07_createCategory(self):
1702
    """ Test to create or clone categories with many users """
1703
    self.login('admin')
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
    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)
1727
    self.login('webmaster')
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    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')
1754

1755
  def test_08_createAndrenameCategory(self):
1756
    """ Test to create or rename categories with many users """
1757
    self.login('admin')
1758 1759
    portal_categories = self.portal.portal_categories
    publication_section = portal_categories.publication_section
1760

1761 1762 1763 1764 1765 1766 1767 1768
    # 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',
1769
      id='new_category_2')
1770 1771
    except Unauthorized:
      self.fail("Admin should be able to create a Category.")
1772
    transaction.commit()
1773 1774
    self.tic()
    try:
1775
      new_cat_1_renamed = new_category_1.edit(id='new_cat_1_renamed')
1776 1777 1778 1779
      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)
1780
    self.login('webmaster')
1781 1782 1783 1784 1785 1786 1787
    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(
Rafael Monnerat's avatar
Rafael Monnerat committed
1788
      portal_type='Category', id='new_category_3')
1789
      new_category_4 = new_category_3.newContent(portal_type='Category',
1790
          id='new_category_4')
1791 1792
    except Unauthorized:
      self.fail("A webmaster should be able to create a Category.")
1793
    transaction.commit()
1794 1795
    self.tic()
    try:
1796
      new_cat_3_renamed = new_category_3.edit(id='new_cat_3_renamed')
1797 1798 1799
      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.")
1800

1801 1802 1803 1804 1805
  def test_getDocumentValueList_AnonymousUser(self):
    """
      For a given Web Site with Predicates:
      - membership_criterion_base_category: follow_up
      - membership_criterion_document_list: follow_up/project/object_id
1806

1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
      When you access website/WebSection_viewContentListAsRSS:
      - with super user you get the correct result
      - with anonymous user you do not get the correct result

      In this case, both Web Pages are returned for Anonymous user and this
      it not the expected behavior.

      Note: The ListBox into WebSection_viewContentListAsRSS has
            getDocumentValueList defined as ListMethod.
    """
    project = self.portal.project_module.newContent(portal_type='Project')
    project.validate()
    self.stepTic()
1820

1821
    website = self.portal.web_site_module.newContent(portal_type='Web Site',
1822
                                                     id='site')
1823
    website.publish()
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
    website.setMembershipCriterionBaseCategory('follow_up')
    website.setMembershipCriterionDocumentList(['follow_up/%s' %
                                                  project.getRelativeUrl()])
    self.stepTic()

    web_page_module = self.portal.web_page_module
    web_page_follow_up = web_page_module.newContent(portal_type="Web Page",
                                      follow_up=project.getRelativeUrl(),
                                      id='test_web_page_with_follow_up',
                                      reference='NXD-Document.Follow.Up.Test',
                                      version='001',
                                      language='en',
                                      text_content='test content')
    web_page_follow_up.publish()
    self.stepTic()
1839

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
    web_page_no_follow_up = web_page_module.newContent(portal_type="Web Page",
                                      id='test_web_page_no_follow_up',
                                      reference='NXD-Document.No.Follow.Up.Test',
                                      version='001',
                                      language='en',
                                      text_content='test content')
    web_page_no_follow_up.publish()
    self.stepTic()

    self.assertEquals(1, len(website.WebSection_getDocumentValueList()))

    self.logout()
    self.assertEquals(1, len(website.WebSection_getDocumentValueList()))

1854 1855
  def test_WebSiteModuleDefaultSecurity(self):
    """
1856
      Test that by default Anonymous User cannot access Web Site Module
1857 1858
    """
    self.logout()
1859
    self.assertRaises(Unauthorized, self.portal.web_site_module.view)
1860

1861

1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
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())

Rafael Monnerat's avatar
Rafael Monnerat committed
1892

1893 1894 1895
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Web))
1896
  suite.addTest(unittest.makeSuite(TestERP5WebWithSimpleSecurity))
1897
  suite.addTest(unittest.makeSuite(TestERP5WebCategoryPublicationWorkflow))
1898
  return suite