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

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

Rafael Monnerat's avatar
Rafael Monnerat committed
45

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

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

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

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

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

76 77
    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
78
    portal.Localizer.manage_changeDefaultLang(language='en')
79 80
    self.portal_id = self.portal.getId()

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

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

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

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

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

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

127
    self.stepTic()
128 129
    return websection

130
  def setupWebSitePages(self, prefix, suffix=None, version='0.1',
131
                        language_list=LANGUAGE_LIST, **kw):
132 133 134 135 136 137 138
    """
      Setup some Web Pages.
    """
    webpage_list = []
    # create sample web pages
    for language in language_list:
      if suffix is not None:
139
        reference = '%s-%s' % (prefix, language)
140 141
      else:
        reference = prefix
142
      webpage = self.web_page_module.newContent(portal_type='Web Page',
143 144 145 146
                                                reference=reference,
                                                version=version,
                                                language=language,
                                                **kw)
147
      webpage.publish()
148
      self.stepTic()
149 150 151 152 153
      self.assertEquals(language, webpage.getLanguage())
      self.assertEquals(reference, webpage.getReference())
      self.assertEquals(version, webpage.getVersion())
      self.assertEquals('published', webpage.getValidationState())
      webpage_list.append(webpage)
154

155
    return webpage_list
156

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

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

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

181
  def test_02a_WebPageAsText(self):
182 183 184 185 186
    """
      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
187
    self.portal.portal_transforms.max_sec_in_cache = -1
188 189
    page = self.web_page_module.newContent(portal_type='Web Page')
    page.edit(text_content='<p>Hé Hé Hé!</p>')
190
    self.stepTic()
191 192
    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>')
193
    self.stepTic()
194 195 196
    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())

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

215
    self.stepTic()
216

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

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

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

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

249
  def test_04_WebPageTranslation(self):
250
    """
251
      Simple Case of showing the proper Web Page based on
252 253 254 255 256 257
      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
258
    webpage_list = self.setupWebSitePages(prefix=page_reference)
259

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

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

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

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

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

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

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

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

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

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

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

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

Ivan Tyagov's avatar
Ivan Tyagov committed
333
    # create pages belonging to this publication_section 'documentation'
Rafael Monnerat's avatar
Rafael Monnerat committed
334 335 336 337 338 339
    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
340
    websection.setAggregateValue(web_page_en)
341
    self.stepTic()
342
    self.assertEqual(None, websection.getDefaultDocumentValue())
Ivan Tyagov's avatar
Ivan Tyagov committed
343 344
    # publish it
    web_page_en.publish()
345
    self.stepTic()
346 347 348 349 350 351 352
    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
353 354
    self.assertEqual(base_url, "%s/%s/" % (websection.absolute_url(),
                                           web_page_en.getReference()))
355

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

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

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

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

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

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

Rafael Monnerat's avatar
Rafael Monnerat committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    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"),
429 430
                    }
    sequence_one = property_dict.keys()
Rafael Monnerat's avatar
Rafael Monnerat committed
431 432 433 434
    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']
435

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

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

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

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

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

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

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

471 472 473 474 475
      # 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
476
                       [w.getLanguage() for w in default_document_value_list])
477

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

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

488 489 490
      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
491
                       [w.getLanguage() for w in bg_document_value_list])
492

493 494 495
      # 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
496 497
      self.assertEqual(['en', 'en', 'en', 'en', 'en'],
                       [w.getLanguage() for w in en_document_value_list])
498 499 500 501

      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
502 503
      self.assertEqual(['pt', 'pt', 'pt', 'pt', 'pt'],
                       [w.getObject().getLanguage() for w in pt_document_value_list])
504

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

      # Tests for all_languages parameter
512 513
      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
514
      self.assertEqual(4, len([w.getLanguage() for w in en_document_value_list \
515
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
516
      self.assertEqual(1, len([w.getLanguage() for w in en_document_value_list \
517
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
518
      self.assertEqual(['3'], [w.getVersion() for w in en_document_value_list \
519
                              if w.getLanguage() == 'pt'])
Rafael Monnerat's avatar
Rafael Monnerat committed
520
      self.assertEqual(1, len([w.getLanguage() for w in en_document_value_list \
521
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
522
      self.assertEqual(['3'], [w.getVersion() for w in en_document_value_list \
523
                              if w.getLanguage() == 'ja'])
524

525 526 527
      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
528
      self.assertEqual(4, len([w.getLanguage() for w in pt_document_value_list \
529
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
530
      self.assertEqual(1, len([w.getLanguage() for w in pt_document_value_list \
531
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
532
      self.assertEqual(['3'], [w.getVersion() for w in pt_document_value_list \
533
                              if w.getLanguage() == 'en'])
Rafael Monnerat's avatar
Rafael Monnerat committed
534
      self.assertEqual(1, len([w.getLanguage() for w in pt_document_value_list \
535
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
536
      self.assertEqual(['3'], [w.getVersion() for w in pt_document_value_list \
537
                              if w.getLanguage() == 'ja'])
538

539 540 541
      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
542
      self.assertEqual(4, len([w.getLanguage() for w in ja_document_value_list \
543
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
544
      self.assertEqual(1, len([w.getLanguage() for w in ja_document_value_list \
545
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
546
      self.assertEqual(['3'], [w.getVersion() for w in ja_document_value_list \
547
                              if w.getLanguage() == 'pt'])
Rafael Monnerat's avatar
Rafael Monnerat committed
548
      self.assertEqual(1, len([w.getLanguage() for w in ja_document_value_list \
549
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
550
      self.assertEqual(['3'], [w.getVersion() for w in ja_document_value_list \
551 552
                            if w.getLanguage() == 'en'])

553 554 555
      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
556
      self.assertEqual(0, len([w.getLanguage() for w in bg_document_value_list \
557
                              if w.getLanguage() == 'bg']))
Rafael Monnerat's avatar
Rafael Monnerat committed
558
      self.assertEqual(3, len([w.getLanguage() for w in bg_document_value_list \
559
                              if w.getLanguage() == 'en']))
Rafael Monnerat's avatar
Rafael Monnerat committed
560
      self.assertEqual(1, len([w.getLanguage() for w in bg_document_value_list \
561
                              if w.getLanguage() == 'pt']))
Rafael Monnerat's avatar
Rafael Monnerat committed
562
      self.assertEqual(['3'], [w.getVersion() for w in bg_document_value_list \
563
                              if w.getLanguage() == 'pt'])
Rafael Monnerat's avatar
Rafael Monnerat committed
564
      self.assertEqual(1, len([w.getLanguage() for w in bg_document_value_list \
565
                              if w.getLanguage() == 'ja']))
Rafael Monnerat's avatar
Rafael Monnerat committed
566
      self.assertEqual(['3'], [w.getVersion() for w in bg_document_value_list \
567 568
                            if w.getLanguage() == 'ja'])

569
      # Tests for all_languages and all_versions
570 571 572 573 574 575 576 577 578 579 580
      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
581
      for document_value_list in [en_document_value_list, pt_document_value_list,
582 583
                                   ja_document_value_list]:

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

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

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

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

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

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

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

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

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

629
      self.web_page_module.manage_delObjects(list(self.web_page_module.objectIds()))
630

631
  def test_08_AcquisitionWrappers(self):
632 633 634 635 636 637 638 639 640 641 642 643
    """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')
644
      self.stepTic()
645 646 647 648 649 650

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

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

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

683
  def test_09_WebSiteSkinSelection(self):
684 685 686 687 688 689 690 691 692
    """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())
693
    self.stepTic()
694 695 696 697 698 699 700 701 702 703

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

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

718
    self.stepTic()
719 720 721 722 723 724 725 726 727 728

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

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

734
  def test_10_getDocumentValueList(self):
735 736 737 738 739 740 741
    """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')])

742
  def test_11_getWebSectionValueList(self):
743 744 745 746 747 748 749 750 751
    """ 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
752
    web_site = self.web_site_module.newContent(portal_type=web_site_portal_type)
753 754 755 756
    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
757
    web_page = self.web_page_module.newContent(portal_type=web_page_portal_type)
758 759 760 761

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

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

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

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

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

872
  def test_13_DocumentCache(self):
873
    """
874
      Test that when a document is modified, it can be accessed through a
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
      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()
892
    self.stepTic()
893 894
    self.assertEquals(document.asText().strip(), 'initial text')

895 896 897 898 899 900 901
    # 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.
902
    path = website.absolute_url_path() + '/NXD-Document.Cache'
903
    response = self.publish(path, self.credential)
904
    self.assertNotEquals(response.getBody().find(content), -1)
905

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

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

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

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

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

      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()
952
    self.stepTic()
953 954 955 956
    self.assertEquals(document.asText().strip(), 'initial text')

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

962
  def test_13b_DocumentEditCacheKey(self):
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    """
      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>'
978
    new_content = '<p>modified text</p>'
979 980 981 982 983
    document = portal.web_page_module.newContent(portal_type='Web Page',
            id='document_cache',
            reference='NXD-Document.Cache',
            text_content=content)
    document.publish()
984
    self.stepTic()
985 986 987 988
    self.assertEquals(document.asText().strip(), 'initial text')

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

    # Modify the web_page content
    # Use unrestrictedTraverse (XXX-JPS reason unknown)
998
    web_document = website.unrestrictedTraverse('web_page_module/%s' % document.getId())
999 1000 1001 1002 1003 1004
    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')
1005
    self.stepTic()
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

    # 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'
1023
    response = self.publish(path, self.credential)
1024
    self.assertNotEquals(response.getBody().find(new_content), -1)
1025 1026 1027 1028 1029

    # 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'
1030
    response = self.publish(path, self.credential)
1031
    self.assertNotEquals(response.getBody().find(new_content), -1)
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  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, {})
1052
    self.stepTic()
1053 1054 1055
    preference_tool = self.getPreferenceTool()
    isTransitionPossible = self.portal.portal_workflow.isTransitionPossible

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

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

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

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

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

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

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

1106
  def test_15_Check_LastModified_Header(self):
Nicolas Delaby's avatar
Nicolas Delaby committed
1107
    """Checks that Last-Modified header set by caching policy manager
1108
    is correctly filled with getModificationDate of content.
1109
    This test check 2 Policy installed by erp5_web:
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    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()
1123
    self.stepTic()
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    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)
1144

1145
  def test_16_404ErrorPageIsReturned(self):
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    """
      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')
1163

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  @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())

1186
    self.stepTic()
1187
    response = self.publish('/%s/%s/%s/%s/Base_editAndEditAsWeb' % \
Rafael Monnerat's avatar
Rafael Monnerat committed
1188
                    (self.portal.getId(), website.getRelativeUrl(),
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
                     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
1201

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

1206
    self.stepTic()
1207 1208 1209

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

1214
    self.stepTic()
1215 1216 1217

    self.assertEquals('%s_edited' % websection.getId(), websection.getTitle())
    self.assertEquals(1, len(self.portal.portal_catalog(
Rafael Monnerat's avatar
Rafael Monnerat committed
1218
                                    relative_url=websection.getRelativeUrl(),
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
                                    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())

1241
    self.stepTic()
1242 1243

    response = self.publish('/%s/%s/%s/Base_editAndEditAsWeb' % \
Rafael Monnerat's avatar
Rafael Monnerat committed
1244
                    (self.portal.getId(), website.getRelativeUrl(),
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
                     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
1257

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

1262
    self.stepTic()
1263 1264 1265

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

1270
    self.stepTic()
1271 1272 1273

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

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

1284 1285 1286 1287
    # 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
1288

1289 1290 1291 1292
    # 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
1293

1294 1295 1296 1297
    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())
1298 1299 1300

  def test_20_reStructuredText(self):
    web_page = self.portal.web_page_module.newContent(portal_type='Web Page',
1301 1302
                                                      content_type='text/x-rst')
    web_page.edit(text_content="`foo`")
1303 1304 1305
    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
1306 1307 1308 1309 1310 1311
  def test_21_WebSiteMap(self):
    """
      Test Web Site map script.
    """
    request = self.app.REQUEST
    website = self.setupWebSite()
Rafael Monnerat's avatar
Rafael Monnerat committed
1312 1313 1314
    kw = {'depth': 5,
          'include_subsection': 1}

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

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

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

1348

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

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

1377 1378 1379 1380
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
    self.tic()

1381
  def beforeTearDown(self):
1382 1383
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
1384

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

    self.tic()

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

    self.tic()

1398
    self.login('erp5user')
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    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!')

    self.tic()

    page_en.publish()

    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='こんにちは、世界!')

    self.tic()

    page_ja.publish()

    self.tic()

    # By Anonymous
    self.logout()

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

1430
    target = self.portal.unrestrictedTraverse('web_site_module/site/section/my-first-web-page')
1431 1432 1433 1434
    self.assertEqual('Hello, World!', target.getTextContent())

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

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

1438
  def test_02_LocalRolesFromRoleDefinition(self):
1439 1440 1441 1442 1443 1444
    """ 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')
1445
    person = portal.person_module.newContent(portal_type = 'Person',
1446
                                             reference = person_reference)
1447
    # add Role Definition for site and section
1448 1449
    site_role_definition = site.newContent(portal_type = 'Role Definition',
                                           role_name = 'Assignee',
1450
                                           agent = person.getRelativeUrl())
1451 1452
    section_role_definition = section.newContent(portal_type = 'Role Definition',
                                                 role_name = 'Associate',
1453
                                                 agent = person.getRelativeUrl())
1454 1455
    self.tic()
    # check if Role Definition have create local roles
1456
    self.assertSameSet(('Assignee',),
1457
                          site.get_local_roles_for_userid(person_reference))
1458
    self.assertSameSet(('Associate',),
1459
                          section.get_local_roles_for_userid(person_reference))
1460 1461
    self.assertRaises(Unauthorized, site_role_definition.edit,
                      role_name='Manager')
1462

1463 1464 1465 1466
    # 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())
    self.tic()
1467
    self.assertSameSet((),
1468 1469 1470 1471
                       site.get_local_roles_for_userid(person_reference))
    self.assertSameSet((),
                       section.get_local_roles_for_userid(person_reference))

1472
  def test_03_WebSection_getDocumentValueListSecurity(self):
1473
    """ Test WebSection_getDocumentValueList behaviour and security"""
1474
    self.login('admin')
1475
    site = self.portal.web_site_module.newContent(portal_type='Web Site',
1476
                                      id='site')
1477
    site.publish()
1478

1479
    section = site.newContent(portal_type='Web Section',
1480 1481 1482 1483 1484
                              id='section')

    self.tic()

    section.setCriterionProperty('portal_type')
1485
    section.setCriterion('portal_type', max='',
1486 1487 1488 1489
                         identity=['Web Page'], min='')

    self.tic()

1490
    self.login('erp5user')
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    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!')

1519
    self.commit()
1520
    self.login('erp5user')
1521 1522
    self.tic()
    self.portal.Localizer.changeLanguage('en')
1523

1524
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))
1525

1526
    self.login('erp5user')
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    page_en_0.publish()
    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()))
1542
    self.assertEquals(page_en_0.getUid(),
1543 1544 1545 1546 1547
                      section.WebSection_getDocumentValueList()[0].getUid())
    self.portal.Localizer.changeLanguage('jp')
    self.assertEquals(0, len(section.WebSection_getDocumentValueList()))

    # Second Object
1548
    self.login('erp5user')
1549 1550 1551 1552 1553
    page_en_1.publish()
    self.tic()

    self.portal.Localizer.changeLanguage('en')
    self.assertEquals(1, len(section.WebSection_getDocumentValueList()))
1554
    self.assertEquals(page_en_1.getUid(),
1555 1556 1557 1558 1559 1560 1561 1562
                      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()))
1563
    self.assertEquals(page_en_1.getUid(),
1564 1565 1566
                      section.WebSection_getDocumentValueList()[0].getUid())

    # Trird Object
1567
    self.login('erp5user')
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
    page_en_2.publish()
    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()))

1583
    # First Japanese Object
1584
    self.login('erp5user')
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    page_jp_0.publish()
    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()))
1599
    self.assertEquals(page_jp_0.getUid(),
1600
                      section.WebSection_getDocumentValueList()[0].getUid())
1601

1602
  def test_04_ExpireUserAction(self):
1603
    """ Test the expire user action"""
1604
    self.login('admin')
1605
    site = self.portal.web_site_module.newContent(portal_type='Web Site', id='site')
1606 1607 1608 1609 1610 1611 1612 1613

    # 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')
1614 1615
    self.tic()

1616 1617 1618 1619 1620 1621
    # 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.")
1622

1623
    # test if a user (ASSIGNOR) can expire them
1624
    self.login('webmaster')
1625 1626 1627 1628 1629
    try:
      section_2.expire()
      section_6.expire()
    except Unauthorized:
      self.fail("An user should be able to expire a Web Section.")
1630

1631
  def test_05_createWebSite(self):
1632
    """ Test to create or clone web sites with many users """
1633
    self.login('admin')
1634
    web_site_module = self.portal.web_site_module
1635 1636 1637 1638 1639 1640 1641 1642

    # 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)
1643
    self.login('webmaster')
1644 1645 1646 1647 1648
    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.")

1649 1650 1651 1652 1653
    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')

1654
  def test_06_createWebSection(self):
1655
    """ Test to create or clone web sections with many users """
1656
    self.login('admin')
1657
    site = self.portal.web_site_module.newContent(portal_type='Web Site', id='site')
1658

1659 1660 1661 1662 1663 1664 1665
    # 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.")

1666
    # test as a webmaster (assignor)
1667
    self.login('webmaster')
1668 1669 1670 1671
    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:
1672
      self.fail("A webmaster should be able to create a Web Section.")
1673 1674 1675 1676 1677 1678 1679 1680
    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')
1681

1682
  def test_07_createCategory(self):
1683
    """ Test to create or clone categories with many users """
1684
    self.login('admin')
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    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)
1708
    self.login('webmaster')
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
    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')
1735

1736
  def test_08_createAndrenameCategory(self):
1737
    """ Test to create or rename categories with many users """
1738
    self.login('admin')
1739 1740
    portal_categories = self.portal.portal_categories
    publication_section = portal_categories.publication_section
1741

1742 1743 1744 1745 1746 1747 1748 1749
    # 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',
1750
      id='new_category_2')
1751 1752 1753 1754
    except Unauthorized:
      self.fail("Admin should be able to create a Category.")
    self.tic()
    try:
1755
      new_cat_1_renamed = new_category_1.edit(id='new_cat_1_renamed')
1756 1757 1758 1759
      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)
1760
    self.login('webmaster')
1761 1762 1763 1764 1765 1766 1767
    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
1768
      portal_type='Category', id='new_category_3')
1769
      new_category_4 = new_category_3.newContent(portal_type='Category',
1770
          id='new_category_4')
1771 1772 1773 1774
    except Unauthorized:
      self.fail("A webmaster should be able to create a Category.")
    self.tic()
    try:
1775
      new_cat_3_renamed = new_category_3.edit(id='new_cat_3_renamed')
1776 1777 1778
      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.")
1779

1780 1781 1782 1783 1784
  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
1785

1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
      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()
1799

1800
    website = self.portal.web_site_module.newContent(portal_type='Web Site',
1801
                                                     id='site')
1802
    website.publish()
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
    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()
1818

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    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()))

1833 1834
  def test_WebSiteModuleDefaultSecurity(self):
    """
1835
      Test that by default Anonymous User cannot access Web Site Module
1836 1837
    """
    self.logout()
1838
    self.assertRaises(Unauthorized, self.portal.web_site_module.view)
1839

1840

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
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
1871

1872 1873 1874
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Web))
1875
  suite.addTest(unittest.makeSuite(TestERP5WebWithSimpleSecurity))
1876
  suite.addTest(unittest.makeSuite(TestERP5WebCategoryPublicationWorkflow))
1877
  return suite