test.erp5.testERP5WebWithDms.py 75.4 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
##############################################################################
#
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
#          Romain Courteaud <romain@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

import unittest
31
import os
32 33
import quopri
import functools
34
from StringIO import StringIO
35
from lxml import etree
36 37
from base64 import b64decode, b64encode
from email.parser import Parser as EmailParser
38

39
import transaction
40 41 42
from AccessControl import Unauthorized
from AccessControl.SecurityManagement import newSecurityManager
from Testing import ZopeTestCase
43
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
Nicolas Delaby's avatar
Nicolas Delaby committed
44
from Products.ERP5Type.tests.utils import FileUpload, createZODBPythonScript
45
from Products.ERP5.Document.Document import ConversionError
Nicolas Delaby's avatar
Nicolas Delaby committed
46

47
from PIL import Image
48 49

LANGUAGE_LIST = ('en', 'fr', 'de', 'bg',)
50
IMAGE_COMPARE_TOLERANCE = 850
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
XSMALL_SVG_IMAGE_ICON_DATA = '''<svg width="30" height="35" xmlns="http://www.w3.org/2000/svg">
  <path d="m5,5l15,0l0,5l5,0l0,20l-20,0z" stroke-width="1.5" stroke="gray" fill="skyblue"/>
  <path d="m6,29l8,-8l5,5l2,-2l3,3l0,2z" stroke-width="0" fill="green"/>
  <path d="m25,10l0,-1l-4,-4l-1,0l0,5z" stroke-width="1.5" stroke="gray" fill="white"/>
  <path d="m8,15c5,-8 10,-2 10,0z" stroke-width="0" fill="white"/>
</svg>'''
XSMALL_PNG_IMAGE_ICON_DATA = b64decode('''
iVBORw0KGgoAAAANSUhEUgAAAB4AAAAjCAIAAAAMti2GAAABkElEQVRIiWP8//8/A20AE43MHbJG
syBzduzY8fLlSyJ1vnv3joGBQUtLy93dnbDRL168ePj0OSO/CDFG///8meH//xMnTvz48cPf35+A
0QwMDIz8ImzWgcQY/XPbbHlpSQEBgQsXLjAwMGCajm40qSAgIICBgQGr6ZQajWw6Ozu7h4cHdYx+
+fLlwoUL4dxr165Rx2hGLr4f3z49ePIMxmdEU0DAaHZmRlNRThMxTg5mxo+//p1+9f3M6+8QKTaH
cGSVv46uF+JhJdZodmbGKFV+cU6oGn42JhcZbnEulq0PPxPwEQMDA57ciGYuHOgKsZuIclJktIsM
D6a5EGAqRpTROANk68PPRHocFxiaJd+o0WQaffbR8jUX8kgymqgyBNncEINJRBpN2NXI5pLkdgJG
Y5pFvE34AgSXzrOPljMwMCgKWeIPJZxG43fR2UfLIRbAbfJjcERTgz1ASE0PcGsIGE1GOsMK0APk
/6e3ek9E9ERmk2rQv49vGHgkcBotISHBQDbglkDTzjjaCKab0QBziJyFukqO6AAAAABJRU5ErkJg
gg==''')

69

70
def makeFilePath(name):
71 72
  from Products.ERP5 import tests
  return os.path.join(tests.__path__[0], 'test_data', name)
73 74 75 76 77 78 79

def makeFileUpload(name, as_name=None):
  if as_name is None:
    as_name = name
  path = makeFilePath(name)
  return FileUpload(path, as_name)

80 81 82 83 84 85 86 87 88 89 90 91 92
def process_image(image, size=(40, 40)):
  # open the images to compare, resize them, and convert to grayscale
  # get the rgb values of the pixels in the image
  image = Image.open(image)
  return list(image.resize(size).convert("L").getdata())

def compare_image(image_data_1, image_data_2):
  """ Find the total difference in RGB value for all pixels in the images
      and return the "amount" of differences that the 2 images contains. """
  data1 = process_image(image_data_1)
  data2 = process_image(image_data_2)
  return abs(sum([data1[x] - data2[x] for x in range(len(data1))]))

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
def customScript(script_id, script_param, script_code):
  def wrapper(func):
    @functools.wraps(func)
    def wrapped(self, *args, **kwargs):
      if script_id in self.portal.portal_skins.custom.objectIds():
        raise ValueError('Precondition failed: %s exists in custom' % script_id)
      createZODBPythonScript(
        self.portal.portal_skins.custom,
        script_id,
        script_param,
        script_code,
      )
      try:
        func(self, *args, **kwargs)
      finally:
        if script_id in self.portal.portal_skins.custom.objectIds():
          self.portal.portal_skins.custom.manage_delObjects(script_id)
        transaction.commit()
    return wrapped
  return wrapper
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
class TestERP5WebWithDms(ERP5TypeTestCase, ZopeTestCase.Functional):
  """Test for erp5_web business template.
  """
  run_all_test = 1
  quiet = 0
  manager_username = 'zope'
  manager_password = 'zope'
  website_id = 'test'

  def getTitle(self):
    return "ERP5WebWithDms"

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

  def getBusinessTemplateList(self):
    """
    Return the list of required business templates.
    """
136 137
    return ('erp5_core_proxy_field_legacy',
            'erp5_base',
Ivan Tyagov's avatar
Ivan Tyagov committed
138 139
            'erp5_jquery',
            'erp5_knowledge_pad',
140
            'erp5_web',
141 142
            'erp5_ingestion',
            'erp5_ingestion_mysql_innodb_catalog',
143
            'erp5_svg_editor',
144 145 146 147 148 149 150 151 152
            'erp5_dms',
            )

  def afterSetUp(self):
    self.login()
    self.web_page_module = self.portal.web_page_module
    self.web_site_module = self.portal.web_site_module
    self.portal_id = self.portal.getId()

153 154 155 156
  def clearModule(self, module):
    module.manage_delObjects(list(module.objectIds()))
    self.tic()

157
  def beforeTearDown(self):
158 159
    self.clearModule(self.portal.web_site_module)
    self.clearModule(self.portal.web_page_module)
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

  def setupWebSite(self, **kw):
    """
      Setup Web Site
    """
    portal = self.getPortal()

    # add supported languages for Localizer
    localizer = portal.Localizer
    for language in LANGUAGE_LIST:
      localizer.manage_addLanguage(language = language)

    # create website
    if hasattr(self.web_site_module, self.website_id):
      self.web_site_module.manage_delObjects(self.website_id)
    website = self.getPortal().web_site_module.newContent(portal_type = 'Web Site',
                                                          id = self.website_id,
                                                          **kw)
178
    website.publish()
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    self.tic()
    return website

  def setupWebSection(self, **kw):
    """
      Setup Web Section
    """
    web_site_module = self.portal.getDefaultModule('Web Site')
    website = web_site_module[self.website_id]
    websection = website.newContent(portal_type='Web Section', **kw)
    self.websection = websection
    kw = dict(criterion_property_list = 'portal_type',
              membership_criterion_base_category_list='',
              membership_criterion_category_list='')
    websection.edit(**kw)
    websection.setCriterion(property='portal_type',
                            identity=['Web Page'],
                            max='',
                            min='')

    self.tic()
    return websection


  def setupWebSitePages(self, prefix, suffix=None, version='0.1',
                        language_list=LANGUAGE_LIST, **kw):
    """
      Setup some Web Pages.
    """
    webpage_list = []
    # create sample web pages
    for language in language_list:
      if suffix is not None:
        reference = '%s-%s' % (prefix, language)
      else:
        reference = prefix
      webpage = self.web_page_module.newContent(portal_type='Web Page',
                                                reference=reference,
                                                version=version,
                                                language=language,
                                                **kw)
      webpage.publish()
      self.tic()
222 223 224 225
      self.assertEqual(language, webpage.getLanguage())
      self.assertEqual(reference, webpage.getReference())
      self.assertEqual(version, webpage.getVersion())
      self.assertEqual('published', webpage.getValidationState())
226 227 228 229 230 231 232 233 234 235 236 237 238 239
      webpage_list.append(webpage)

    return webpage_list

  def test_01_WebPageVersioning(self, quiet=quiet, run=run_all_test):
    """
      Simple Case of showing the proper most recent public Web Page based on
      (language, version)
    """
    if not run: return
    if not quiet:
      message = '\ntest_01_WebPageVersioning'
      ZopeTestCase._print(message)
    portal = self.getPortal()
240
    self.setupWebSite()
241 242
    websection = self.setupWebSection()
    page_reference = 'default-webpage-versionning'
243
    self.setupWebSitePages(prefix = page_reference)
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

    # set default web page for section
    found_by_reference = portal.portal_catalog(reference = page_reference,
                                               language = 'en',
                                               portal_type = 'Web Page')
    en_01 =  found_by_reference[0].getObject()
    # set it as default web page for section
    websection.edit(categories_list = ['aggregate/%s' %en_01.getRelativeUrl(),])
    self.assertEqual([en_01.getReference(),],
                      websection.getAggregateReferenceList())

    # create manually a copy of 'en_01' with higher version and check that
    # older version is archived and new one is show as default web page for section
    en_02 = self.web_page_module.newContent(portal_type = 'Web Page',
                                            reference = page_reference,
                                            version = 0.2,
                                            language = 'en')
    en_02.publish()
    en_02.reindexObject()
    self.tic()

    # is old archived?
266
    self.assertEqual('archived', en_01.getValidationState())
267 268 269 270

    # is new public and default web page for section?
    portal.Localizer.manage_changeDefaultLang(language = 'en')
    default_document = websection.getDefaultDocumentValue()
271 272 273 274
    self.assertEqual(en_02, default_document)
    self.assertEqual('en', default_document.getLanguage())
    self.assertEqual('0.2', default_document.getVersion())
    self.assertEqual('published', default_document.getValidationState())
275 276 277 278 279 280 281 282 283 284 285 286 287

  def test_02_WebSectionAuthorizationForced(self, quiet=quiet, run=run_all_test):
    """ Check that when a document is requested within a Web Section we have a chance to
        require user to login.
        Whether or not an user will login is controlled by a property on Web Section (authorization_forced).
    """
    if not run: return
    if not quiet:
      message = '\ntest_02_WebSectionAuthorizationForced'
      ZopeTestCase._print(message)
    request = self.app.REQUEST
    website = self.setupWebSite()
    websection = self.setupWebSection()
288
    self.setupWebSitePages(prefix = 'test-web-page')
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    document_reference = 'default-document-reference'
    document = self.portal.web_page_module.newContent(
                                      portal_type = 'Web Page',
                                      reference = document_reference)
    document.release()
    website.setAuthorizationForced(0)
    websection.setAuthorizationForced(0)
    self.tic()

    # make sure that _getExtensibleContent will return the same document
    # there's not other way to test otherwise URL traversal
    self.assertEqual(document.getUid(),
                           websection._getExtensibleContent(request,  document_reference).getUid())

    # Anonymous User should have in the request header for not found when
    # viewing non available document in Web Section (with no authorization_forced)
    self.logout()
    self.assertEqual(None,  websection._getExtensibleContent(request,  document_reference))
307 308 309
    path = websection.absolute_url_path() + '/' + document_reference
    response = self.publish(path)
    self.assertEqual(404, response.getStatus())
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

    # set authorization_forced flag
    self.login()
    websection.setAuthorizationForced(1)

    # check Unauthorized exception is raised for anonymous
    # this exception is usually caught and user is redirecetd to login form
    self.logout()
    self.assertRaises(Unauthorized,  websection._getExtensibleContent,  request,  document_reference)

  def test_03_LatestContent(self, quiet=quiet, run=run_all_test):
    """ Test latest content for a Web Section. Test different use case like languaeg, workflow state.
   """
    if not run: return
    if not quiet:
      message = '\ntest_03_LatestContent'
      ZopeTestCase._print(message)
    portal = self.getPortal()
328
    self.setupWebSite()
329 330 331 332 333 334 335 336 337 338 339 340
    websection = self.setupWebSection()
    portal_categories = portal.portal_categories
    publication_section_category_id_list = ['documentation',  'administration']
    for category_id in publication_section_category_id_list:
      portal_categories.publication_section.newContent(portal_type = 'Category',
                                                                             id = category_id)
    #set predicate on web section using 'publication_section'
    websection.edit(membership_criterion_base_category = ['publication_section'],
                            membership_criterion_category=['publication_section/%s'
                                                                              %publication_section_category_id_list[0]])
    self.tic()

341
    self.assertEqual(0,  len(websection.getDocumentValueList()))
342 343 344 345 346 347
    # create pages belonging to this publication_section 'documentation'
    web_page_en = portal.web_page_module.newContent(portal_type = 'Web Page',
                                                 language = 'en',
                                                 publication_section_list=publication_section_category_id_list[:1])
    web_page_en.publish()
    self.tic()
348 349
    self.assertEqual(1,  len(websection.getDocumentValueList(language='en')))
    self.assertEqual(web_page_en,  websection.getDocumentValueList(language='en')[0].getObject())
350 351 352 353 354 355 356

    # create pages belonging to this publication_section 'documentation' but for 'bg' language
    web_page_bg = portal.web_page_module.newContent(portal_type = 'Web Page',
                                                 language = 'bg',
                                                 publication_section_list=publication_section_category_id_list[:1])
    web_page_bg.publish()
    self.tic()
357 358
    self.assertEqual(1,  len(websection.getDocumentValueList(language='bg')))
    self.assertEqual(web_page_bg,  websection.getDocumentValueList(language='bg')[0].getObject())
359 360 361 362

    # reject page
    web_page_bg.reject()
    self.tic()
363
    self.assertEqual(0,  len(websection.getDocumentValueList(language='bg')))
364 365 366 367

    # publish page and search without a language (by default system should return 'en' docs only)
    web_page_bg.publish()
    self.tic()
368 369
    self.assertEqual(1,  len(websection.getDocumentValueList()))
    self.assertEqual(web_page_en,  websection.getDocumentValueList()[0].getObject())
370 371 372 373 374 375 376 377 378 379

  def test_04_WebSectionAuthorizationForcedForDefaultDocument(self, quiet=quiet, run=run_all_test):
    """ Check that when a Web Section contains a default document not accessible by user we have a chance to
        require user to login.
        Whether or not an user will login is controlled by a property on Web Section (authorization_forced).
    """
    if not run: return
    if not quiet:
      message = '\ntest_04_WebSectionAuthorizationForcedForDefaultDocument'
      ZopeTestCase._print(message)
380
    self.setupWebSite()
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    websection = self.setupWebSection()
    web_page_reference = 'default-document-reference'
    web_page_en = self.portal.web_page_module.newContent(
                                      portal_type = 'Web Page',
                                      language = 'en',
                                      reference = web_page_reference)
    # this way it's not viewable by anonymous and we can test
    web_page_en.releaseAlive()
    websection.setAggregateValue(web_page_en)
    websection.setAuthorizationForced(1)
    self.tic()

    # make sure that getDefaultDocumentValue() will return the same document for logged in user
    # if default document is accessible
    self.assertEqual(web_page_en.getUid(),
                           websection.getDefaultDocumentValue().getUid())

    # check Unauthorized exception is raised for anonymous when authorization_forced is set
    self.logout()
    self.assertEqual(None,  websection.getDefaultDocumentValue())
    self.assertRaises(Unauthorized,  websection)

    # Anonymous User should not get Unauthorized when authorization_forced is not set
    self.login()
    websection.setAuthorizationForced(0)
    self.tic()

    self.logout()
    self.assertEqual(None,  websection.getDefaultDocumentValue())
    try:
      websection()
    except Unauthorized:
      self.fail("Web Section should not prompt user for login.")

    self.login()
    web_page_list = []
    for iteration in range(0, 10):
      web_page =self.getPortal().web_page_module.newContent(portal_type = 'Web Page',
                                                            reference = "%s_%s" % (web_page_reference, iteration),
                                                            language = 'en',)
      web_page.publish()
      self.tic()
423
      self.commit()
424 425 426
      web_page_list.append(web_page)
    websection.setAggregateValueList(web_page_list)
    self.tic()
427
    self.commit()
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    self.assertEqual(5, len(websection.getDocumentValueList(limit=5)))

  def test_05_deadProxyFields(self, quiet=quiet, run=run_all_test):
    """
    check that all proxy fields defined in business templates have a valid
     target
    """
    if not run: return
    if not quiet:
      message = '\ntest_05_deadProxyFields'
      ZopeTestCase._print(message)
    skins_tool = self.portal.portal_skins
    for field_path, field in skins_tool.ZopeFind(
              skins_tool, obj_metatypes=['ProxyField'], search_sub=1):
      self.assertNotEqual(None, field.getTemplateField(),
          '%s\nform_id:%s\nfield_id:%s\n' % (field_path,
                                             field.get_value('form_id'),
                                             field.get_value('field_id')))

447 448 449 450 451 452
  def test_06_Check_LastModified_Header(self):
    """Checks that Last-Modified header set by caching policy manager
    is correctly filled with getModificationDate of content.
    This test check "unauthenticated" Policy installed by erp5_web:
    """
    website = self.setupWebSite()
453 454
    website_url = website.absolute_url_path()
    response = self.publish(website_url)
455 456 457
    self.assertTrue(response.getHeader('x-cache-headers-set-by'),
                    'CachingPolicyManager: /erp5/caching_policy_manager')

458 459
    web_section_portal_type = 'Web Section'
    web_section = website.newContent(portal_type=web_section_portal_type)
460
    response = self.publish(web_section.absolute_url_path())
461 462
    self.assertTrue(response.getHeader('x-cache-headers-set-by'),
                    'CachingPolicyManager: /erp5/caching_policy_manager')
463 464 465 466 467 468 469

    # unauthenticated
    document_portal_type = 'Text'
    document_module = self.portal.getDefaultModule(document_portal_type)
    document = document_module.newContent(portal_type=document_portal_type,
                                          reference='NXD-Document-TEXT.Cache')
    document.publish()
470 471
    # Evaluation of last modification date for the site is cached
    self.portal.portal_caches.clearCache(cache_factory_list=('erp5_content_short', ))
472
    self.tic()
473
    response = self.publish(website_url + '/NXD-Document-TEXT.Cache')
474 475 476 477 478 479 480
    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)

481 482 483 484 485 486 487
    # Upload a presentation with 3 pages.
    upload_file = makeFileUpload('P-DMS-Presentation.3.Pages-001-en.odp')
    document = document_module.newContent(portal_type='Presentation',
                                          file=upload_file)
    reference = 'P-DMS-Presentation.3.Pages'
    document.edit(reference=reference)
    document.publish()
488
    self.portal.portal_caches.clearCache(cache_factory_list=('erp5_content_short', ))
489 490 491 492
    self.tic()
    # Check we can access to the 3 drawings converted into images.
    # Those images can be accessible through extensible content
    # url : path-of-document + '/' + 'img' + page-index + '.png'
493 494
    policy_list = self.portal.caching_policy_manager.listPolicies()
    policy = [policy[1] for policy in policy_list\
495
                if policy[0] == 'unauthenticated no language'][0]
496
    for i in xrange(3):
497 498 499 500
      path = '/'.join((website_url,
                       reference,
                       'img%s.png' % i))
      response = self.publish(path)
501 502
      policy_list = self.portal.caching_policy_manager.listPolicies()
      policy = [policy for policy in policy_list\
503
                                          if policy[0] == 'unauthenticated no language'][0]
504
      self.assertEquals(response.getHeader('Content-Type'), 'image/png')
505 506 507 508 509 510 511
      self.assertEquals(
        response.getHeader('Cache-Control'),
        'max-age=%s, stale-while-revalidate=%s, public' % (
          policy[1].getMaxAgeSecs(),
          policy[1].getStaleWhileRevalidateSecs(),
        )
      )
512

513 514 515 516 517 518 519 520 521 522 523 524 525 526
  def test_07_TestDocumentViewBehaviour(self):
    """All Documents shared the same downloading behaviour
    The rules are.
      a document is allways returned in its web_site envrironment
      except if conversion parameters are passed like format, display, ...

    All links to an image must be write with a parameter in its url
    ../REFERENCE.TO.IMAGE?format=png or ../REFERENCE.TO.IMAGE?display=small
    """
    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
    website = self.setupWebSite()
    web_section_portal_type = 'Web Section'
527
    website.newContent(portal_type=web_section_portal_type)
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556

    web_page_reference = 'NXD-WEB-PAGE'
    content = '<p>initial text</p>'
    web_page_module = portal.getDefaultModule(portal_type='Web Page')
    web_page = web_page_module.newContent(portal_type='Web Page',
                                          reference=web_page_reference,
                                          text_content=content)
    web_page.publish()

    document_reference = 'NXD-Presentation'
    document_module = portal.getDefaultModule(portal_type='Presentation')
    upload_file = makeFileUpload('P-DMS-Presentation.3.Pages-001-en.odp')
    document = document_module.newContent(portal_type='Presentation',
                                          reference=document_reference,
                                          file=upload_file)
    document.publish()

    image_reference = 'NXD-IMAGE'
    image_module = portal.getDefaultModule(portal_type='Image')
    upload_file = makeFileUpload('tiolive-ERP5.Freedom.TioLive.Logo-001-en.png')
    image = image_module.newContent(portal_type='Image',
                                    file=upload_file,
                                    reference=image_reference)
    image.publish()
    self.tic()
    credential = 'ERP5TypeTestCase:'
    # testing TextDocument
    response = self.publish(website.absolute_url_path() + '/' +\
                            web_page_reference, credential)
557
    self.assertEqual(response.getHeader('content-type'),
558 559 560 561 562
                                         'text/html; charset=utf-8')
    self.assertTrue('<form' in response.getBody()) # means the web_page
                                      # is rendered in web_site context

    response = self.publish(website.absolute_url_path() + '/' +\
563
                            web_page_reference, credential)
564
    self.assertEqual(response.getHeader('content-type'),
565 566 567 568 569 570
                                         'text/html; charset=utf-8')
    self.assertTrue('<form' in response.getBody()) # means the web_page
                                      # is rendered in web_site context

    response = self.publish(website.absolute_url_path() + '/' +\
                            web_page_reference + '?format=pdf', credential)
571
    self.assertEqual(response.getHeader('content-type'), 'application/pdf')
572 573 574 575 576

    # testing Image
    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference, credential)
    # image is rendered in web_site context
577
    self.assertEqual(response.getHeader('content-type'),
578 579 580 581 582
                                         'text/html; charset=utf-8')

    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?format=png', credential)
    # image is downloaded because format parameter is passed
583
    self.assertEqual(response.getHeader('content-type'), 'image/png')
584 585 586 587

    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?display=small', credential)
    # image is downloaded because display parameter is passed
588
    self.assertEqual(response.getHeader('content-type'), 'image/png')
589 590 591

    # image is rendered in web_site context
    response = self.publish(website.absolute_url_path() + '/' +\
592
                            image_reference, credential)
593
    self.assertEqual(response.getHeader('content-type'),
594 595 596 597 598 599
                                         'text/html; charset=utf-8')

    # testing OOoDocument
    # Document is downloaded
    response = self.publish(website.absolute_url_path() + '/' +\
                            document_reference, credential)
600
    self.assertEqual(response.getHeader('content-type'),
601 602 603 604
                                         'text/html; charset=utf-8')
    response = self.publish(website.absolute_url_path() + '/' +\
                            document_reference + '?format=odp', credential)
    # document is resturned because format parameter is passed
605
    self.assertEqual(response.getHeader('content-type'),
606 607 608
                      'application/vnd.oasis.opendocument.presentation')
    # Document is rendered in web_site context
    response = self.publish(website.absolute_url_path() + '/' +\
609
                            document_reference, credential)
610
    self.assertEqual(response.getHeader('content-type'),
611 612
                                         'text/html; charset=utf-8')

Aurel's avatar
Aurel committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
  def test_08_RFC5861(self):
    """
    Checks that RFC5861 is well implemented
    """
    website = self.setupWebSite()
    website_url = website.absolute_url_path()
    response = self.publish(website_url)
    self.assertTrue(response.getHeader('x-cache-headers-set-by'),
                    'CachingPolicyManager: /erp5/caching_policy_manager')
    web_section_portal_type = 'Web Section'
    web_section = website.newContent(portal_type=web_section_portal_type)
    response = self.publish(web_section.absolute_url_path())
    self.assertTrue(response.getHeader('x-cache-headers-set-by'),
                    'CachingPolicyManager: /erp5/caching_policy_manager')

    # unauthenticated
    document_portal_type = 'Text'
    document_module = self.portal.getDefaultModule(document_portal_type)
    document = document_module.newContent(portal_type=document_portal_type,
                                          reference='NXD-Document-1-TEXT.Cache')
    document.publish()
634 635
    # Evaluation of last modification date for the site is cached
    self.portal.portal_caches.clearCache(cache_factory_list=('erp5_content_short', ))
Aurel's avatar
Aurel committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    self.tic()
    response = self.publish(website_url + '/NXD-Document-1-TEXT.Cache')
    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)

    # Upload a presentation with 3 pages.
    upload_file = makeFileUpload('P-DMS-Presentation.3.Pages-001-en.odp')
    document = document_module.newContent(portal_type='Presentation',
                                          file=upload_file)
    reference = 'P-DMS-Presentation-001-.3.Pages'
    document.edit(reference=reference)
    document.publish()
652
    self.portal.portal_caches.clearCache(cache_factory_list=('erp5_content_short', ))
Aurel's avatar
Aurel committed
653 654 655 656 657 658
    self.tic()
    # Check we can access to the 3 drawings converted into images.
    # Those images can be accessible through extensible content
    # url : path-of-document + '/' + 'img' + page-index + '.png'
    # Update policy to have stale values
    self.portal.caching_policy_manager._updatePolicy(
659
      "unauthenticated no language", "python: member is None",
Aurel's avatar
Aurel committed
660 661 662 663 664 665
      "python: getattr(object, 'getModificationDate', object.modified)()",
      1200, 30, 600, 0, 0, 0, "Accept-Language, Cookie", "", None,
      0, 1, 0, 0, 1, 1, None, None)
    self.tic()
    policy_list = self.portal.caching_policy_manager.listPolicies()
    policy = [policy[1] for policy in policy_list\
666
                if policy[0] == 'unauthenticated no language'][0]
Aurel's avatar
Aurel committed
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    # Check policy has been updated
    self.assertEquals(policy.getMaxAgeSecs(), 1200)
    self.assertEquals(policy.getStaleWhileRevalidateSecs(), 30)
    self.assertEquals(policy.getStaleIfErrorSecs(), 600)
    for i in xrange(3):
      path = '/'.join((website_url,
                       reference,
                       'img%s.png' % i))
      response = self.publish(path)
      self.assertEquals(response.getHeader('Content-Type'), 'image/png')
      self.assertEquals(response.getHeader('Cache-Control'),
            'max-age=%d, stale-while-revalidate=%d, stale-if-error=%d, public' % \
                          (policy.getMaxAgeSecs(),
                           policy.getStaleWhileRevalidateSecs(),
                           policy.getStaleIfErrorSecs()))


684 685
  def test_PreviewOOoDocumentWithEmbeddedImage(self):
    """Tests html preview of an OOo document with images as extensible content.
Nicolas Delaby's avatar
Nicolas Delaby committed
686 687
    For this test, Presentation_checkConversionFormatPermission does not allow
    access to original format for Unauthenticated users.
688
    Check that user can still access to other format.
689 690
    """
    portal = self.portal
Nicolas Delaby's avatar
Nicolas Delaby committed
691 692 693 694 695 696 697 698 699
    script_id = 'Presentation_checkConversionFormatPermission'
    python_code = """from AccessControl import getSecurityManager
user = getSecurityManager().getUser()
if (not user or not user.getId()) and not format:
  return False
return True
"""
    createZODBPythonScript(portal.portal_skins.custom, script_id,
                           'format, **kw', python_code)
700

701 702
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
703 704
    self.getPortalObject().aq_parent.acl_users._doAddUser(
      'zope_user', '', ['Manager',], [])
705 706
    website = self.setupWebSite()
    web_section_portal_type = 'Web Section'
707
    website.newContent(portal_type=web_section_portal_type)
708 709 710 711 712 713 714 715

    document_reference = 'tiolive-ERP5.Freedom.TioLive'
    upload_file = makeFileUpload('tiolive-ERP5.Freedom.TioLive-001-en.odp')
    document = self.portal.document_module.newContent(
                                          portal_type='Presentation',
                                          reference=document_reference,
                                          file=upload_file)
    self.tic()
716 717 718 719 720 721
    credential_list = ['ERP5TypeTestCase:', 'zope_user:']

    for credential in credential_list:
      # first, preview the draft in its physical location (in document module)
      response = self.publish('%s/asEntireHTML' % document.absolute_url_path(),
                              credential)
722
      self.assertTrue(response.getHeader('content-type').startswith('text/html'))
723 724 725 726 727
      html = response.getBody()
      self.assertTrue('<img' in html, html)

      # find the img src
      img_list = etree.HTML(html).findall('.//img')
728
      self.assertEqual(1, len(img_list))
729 730 731 732 733
      src = img_list[0].get('src')

      # and make another query for this img
      response = self.publish('%s/%s' % ( document.absolute_url_path(), src),
                              credential)
734
      self.assertEqual(response.getHeader('content-type'), 'image/png')
735 736
      png = response.getBody()
      self.assertTrue(png.startswith('\x89PNG'))
737 738 739 740

    # then publish the document and access it anonymously by reference through
    # the web site
    document.publish()
Nicolas Delaby's avatar
Nicolas Delaby committed
741

742 743 744 745
    self.tic()

    response = self.publish('%s/%s/asEntireHTML' % (
              website.absolute_url_path(), document_reference))
746
    self.assertTrue(response.getHeader('content-type').startswith('text/html'))
747 748
    html = response.getBody()
    self.assertTrue('<img' in html, html)
Nicolas Delaby's avatar
Nicolas Delaby committed
749

750
    # find the img src
Jérome Perrin's avatar
Jérome Perrin committed
751
    img_list = etree.HTML(html).findall('.//img')
752
    self.assertEqual(1, len(img_list))
753 754 755 756 757
    src = img_list[0].get('src')

    # and make another query for this img
    response = self.publish('%s/%s/%s' % (
           website.absolute_url_path(), document_reference, src))
758
    self.assertEqual(response.getHeader('content-type'), 'image/png')
759 760 761
    png = response.getBody()
    self.assertTrue(png.startswith('\x89PNG'))

Nicolas Delaby's avatar
Nicolas Delaby committed
762 763 764 765 766 767 768 769 770
    # Now purge cache and let Anonymous user converting the document.
    self.login()
    document.edit() # Reset cache key
    self.tic()
    response = self.publish('%s/%s/asEntireHTML' % (
                            website.absolute_url_path(), document_reference))
    self.assertTrue(response.getHeader('content-type').startswith('text/html'))
    html = response.getBody()
    self.assertTrue('<img' in html, html)
771

Nicolas Delaby's avatar
Nicolas Delaby committed
772 773
    # find the img src
    img_list = etree.HTML(html).findall('.//img')
774
    self.assertEqual(1, len(img_list))
Nicolas Delaby's avatar
Nicolas Delaby committed
775 776
    src = img_list[0].get('src')

777 778 779 780 781
  def test_ImageConversionThroughWebSite_using_file(self):
    """Check that conversion parameters pass in url
    are hounoured to display an image in context of a website
    """
    self.test_ImageConversionThroughWebSite("File")
782

783
  def test_ImageConversionThroughWebSite(self, image_portal_type="Image"):
784 785 786 787 788 789 790 791
    """Check that conversion parameters pass in url
    are hounoured to display an image in context of a website
    """
    portal = self.getPortal()
    request = portal.REQUEST
    request['PARENTS'] = [self.app]
    website = self.setupWebSite()
    web_section_portal_type = 'Web Section'
792
    website.newContent(portal_type=web_section_portal_type)
793 794 795 796 797 798 799 800 801 802 803

    web_page_reference = 'NXD-WEB-PAGE'
    content = '<p>initial text</p>'
    web_page_module = portal.getDefaultModule(portal_type='Web Page')
    web_page = web_page_module.newContent(portal_type='Web Page',
                                          reference=web_page_reference,
                                          text_content=content)
    web_page.publish()


    image_reference = 'NXD-IMAGE'
804
    module = portal.getDefaultModule(portal_type=image_portal_type)
805
    upload_file = makeFileUpload('tiolive-ERP5.Freedom.TioLive.Logo-001-en.png')
806
    image = module.newContent(portal_type=image_portal_type,
807 808 809 810 811
                                    file=upload_file,
                                    reference=image_reference)
    image.publish()
    self.tic()
    credential = 'ERP5TypeTestCase:'
812

813 814 815 816
    # testing Image conversions, raw

    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?format=', credential)
817
    self.assertEqual(response.getHeader('content-type'), 'image/png')
818 819 820 821

    # testing Image conversions, png
    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?format=png', credential)
822
    self.assertEqual(response.getHeader('content-type'), 'image/png')
823 824 825 826

    # testing Image conversions, jpg
    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?format=jpg', credential)
827
    self.assertEqual(response.getHeader('content-type'), 'image/jpeg')
828

829
    # testing Image conversions, svg
830 831
    # disable Image permissiions checks format checks
    createZODBPythonScript(portal.portal_skins.custom, 'Image_checkConversionFormatPermission',
832
                           '**kw', 'return 1')
833 834
    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?format=svg', credential)
835
    self.assertEqual(response.getHeader('content-type'), 'image/svg+xml')
836

837 838 839
    # testing Image conversions, resizing
    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?display=large', credential)
840
    self.assertEqual(response.getHeader('content-type'), 'image/png')
841 842 843
    large_image = response.getBody()
    response = self.publish(website.absolute_url_path() + '/' +\
                            image_reference + '?display=small', credential)
844
    self.assertEqual(response.getHeader('content-type'), 'image/png')
845 846 847 848
    small_image = response.getBody()
    # if larger image is longer than smaller, then
    # Resizing works
    self.assertTrue(len(large_image) > len(small_image))
849

850
  def _test_document_publication_workflow(self, portal_type, transition):
851
    super(TestERP5WebWithDms, self).login()
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    document = self.portal.web_page_module.newContent(portal_type=portal_type)
    self.portal.portal_workflow.doActionFor(document, transition)

  def test_document_publication_workflow_WebPage_publish(self):
    self._test_document_publication_workflow('Web Page', 'publish_action')

  def test_document_publication_workflow_WebPage_publish_alive(self):
    self._test_document_publication_workflow('Web Page',
        'publish_alive_action')

  def test_document_publication_workflow_WebPage_release(self):
    self._test_document_publication_workflow('Web Page', 'release_action')

  def test_document_publication_workflow_WebPage_release_alive(self):
    self._test_document_publication_workflow('Web Page',
        'release_alive_action')

  def test_document_publication_workflow_WebPage_share(self):
    self._test_document_publication_workflow('Web Page', 'share_action')

  def test_document_publication_workflow_WebPage_share_alive(self):
    self._test_document_publication_workflow('Web Page',
        'share_alive_action')

876
  def _testImageConversionFromSVGToPNG(self, portal_type="Image",
877 878 879
                                       filename="user-TESTSVG-CASE-EMBEDDEDDATA"):
    """ Test Convert one SVG Image (Image, TextDocument, File ...) to
        PNG and compare the generated image is well generated.
880 881
    """
    portal = self.portal
882 883 884
    module = portal.getDefaultModule(portal_type=portal_type)
    upload_file = makeFileUpload('%s.svg' % filename)
    image = module.newContent(portal_type=portal_type,
885
                                    file=upload_file,
886
                                    reference="NXD-DOCUMENT")
887 888
    image.publish()
    self.tic()
889
    self.assertEqual(image.getContentType(), 'image/svg+xml')
890
    mime, converted_data = image.convert("png")
891
    self.assertEqual(mime, 'image/png')
892
    expected_image = makeFileUpload('%s.png' % filename)
893 894 895

    # Compare images and accept some minimal difference,
    difference_value = compare_image(StringIO(converted_data), expected_image)
896
    self.assertTrue(difference_value < IMAGE_COMPARE_TOLERANCE,
897
      "Conversion from svg to png create one too small image, " + \
898 899
      "so it failed to download the image. (%s >= %s)" % (difference_value,
                                                          IMAGE_COMPARE_TOLERANCE))
900

901 902 903
  def _testImageConversionFromSVGToPNG_url(self, image_url, portal_type="Image"):
    """ Test Convert one SVG Image with an image url. ie:
         <image xlink:href="xxx:///../../user-XXX-XXX"
904 905
    """
    portal = self.portal
906
    module = portal.getDefaultModule(portal_type=portal_type)
907 908
    upload_file = makeFileUpload('user-TESTSVG-CASE-URL-TEMPLATE.svg')
    svg_content = upload_file.read().replace("REPLACE_THE_URL_HERE", image_url)
909 910 911

    # Add image using data instead file this time as it is not the goal of
    # This test assert this topic.
912
    image = module.newContent(portal_type=portal_type,
913 914 915
                                    data=svg_content,
                                    filename=upload_file.filename,
                                    content_type="image/svg+xml",
916
                                    reference="NXD-DOCYMENT")
917 918
    image.publish()
    self.tic()
919
    self.assertEqual(image.getContentType(), 'image/svg+xml')
920
    mime, converted_data = image.convert("png")
921
    self.assertEqual(mime, 'image/png')
922
    expected_image = makeFileUpload('user-TESTSVG-CASE-URL.png')
923 924 925

    # Compare images and accept some minimal difference,
    difference_value = compare_image(StringIO(converted_data), expected_image)
926
    self.assertTrue(difference_value < IMAGE_COMPARE_TOLERANCE,
927
      "Conversion from svg to png create one too small image, " + \
928 929
      "so it failed to download the image. (%s >= %s)" % (difference_value,
                                                           IMAGE_COMPARE_TOLERANCE))
930

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
  def _testImageConversionFromSVGToPNG_file_url(self, portal_type="Image"):
    """ Test Convert one SVG Image with an image using local path (file)
        at the url of the image tag. ie:
         <image xlink:href="file:///../../user-XXX-XXX"

        This is not used by ERP5 in production, but this is way that
        prooves that conversion from SVG to PNG can use external images.
    """
    image_url = "file://" + makeFilePath("user-TESTSVG-BACKGROUND-IMAGE.png")
    self._testImageConversionFromSVGToPNG_url(image_url, portal_type)

  def _testImageConversionFromSVGToPNG_http_url(self, portal_type="Image"):
    """ Test Convert one SVG Image with an image with a full
        url at the url of the image tag. ie:
         <image xlink:href="http://www.erp5.com/user-XXX-XXX"
    """
    portal = self.portal
    module = portal.getDefaultModule(portal_type=portal_type)
    upload_file = makeFileUpload('user-TESTSVG-BACKGROUND-IMAGE.png')
    background_image = module.newContent(portal_type=portal_type,
                                    file=upload_file,
                                    reference="NXD-BACKGROUND")
    background_image.publish()
    self.tic()

    image_url = background_image.absolute_url() + "?format="
    self._testImageConversionFromSVGToPNG_url(image_url, portal_type)

959 960 961 962 963 964 965 966 967 968 969
  def _testImageConversionFromSVGToPNG_broken_url(self, portal_type="Image"):
    """ Test Convert one broken SVG into PNG. The expected outcome is a
        conversion error when an SVG contains one unreacheble xlink:href like.
        at the url of the image tag. ie:
         <image xlink:href="http://soidjsoidjqsoijdqsoidjqsdoijsqd.idjsijds/../user-XXX-XXX"

        This is not used by ERP5 in production, but this is way that
        prooves that conversion from SVG to PNG can use external images.
    """
    portal = self.portal
    module = portal.getDefaultModule(portal_type=portal_type)
970
    upload_file = makeFileUpload('user-TESTSVG-CASE-URL-TEMPLATE.svg')
971 972 973
    svg_content = upload_file.read().replace("REPLACE_THE_URL_HERE",
                           "http://soidjsoidjqsoijdqsoidjqsdoijsqd.idjsijds/../user-XXX-XXX")

974
    upload_file = makeFileUpload('user-TESTSVG-CASE-URL-TEMPLATE.svg')
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
    svg2_content = upload_file.read().replace("REPLACE_THE_URL_HERE",
                           "https://www.erp5.com/usXXX-XXX")


    # Add image using data instead file this time as it is not the goal of
    # This test assert this topic.
    image = module.newContent(portal_type=portal_type,
                                    data=svg_content,
                                    filename=upload_file.filename,
                                    content_type="image/svg+xml",
                                    reference="NXD-DOCYMENT")
    # Add image using data instead file this time as it is not the goal of
    # This test assert this topic.
    image2 = module.newContent(portal_type=portal_type,
                                    data=svg2_content,
                                    filename=upload_file.filename,
                                    content_type="image/svg+xml",
                                    reference="NXD-DOCYMENT2")

    image.publish()
    image2.publish()
    self.tic()
997 998
    self.assertEqual(image.getContentType(), 'image/svg+xml')
    self.assertEqual(image2.getContentType(), 'image/svg+xml')
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    self.assertRaises(ConversionError, image.convert, "png")
    self.assertRaises(ConversionError, image2.convert, "png")

  def _testImageConversionFromSVGToPNG_empty_file(self, portal_type="Image"):
    """ Test Convert one empty SVG into PNG. The expected outcome is ???
    """
    portal = self.portal
    module = portal.getDefaultModule(portal_type=portal_type)


    # Add image using data instead file this time as it is not the goal of
    # This test assert this topic.
    image = module.newContent(portal_type=portal_type,
                                    content_type="image/svg+xml",
                                    reference="NXD-DOCYMENT")

    image.publish()
    self.tic()
1017
    self.assertEqual(image.getContentType(), 'image/svg+xml')
1018 1019
    self.assertRaises(ConversionError, image.convert, "png")

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  def test_ImageConversionFromSVGToPNG_embeeded_data(self):
    """ Test Convert one SVG Image with an image with the data
        at the url of the image tag.ie:
         <image xlink:href="data:...." >
    """
    self._testImageConversionFromSVGToPNG("Image")

  def test_FileConversionFromSVGToPNG_embeeded_data(self):
    """ Test Convert one SVG Image with an image with the data
        at the url of the image tag.ie:
         <image xlink:href="data:...." >
    """
    self._testImageConversionFromSVGToPNG("File")
1033

1034 1035 1036 1037 1038 1039 1040
  def test_WebPageConversionFromSVGToPNG_embeeded_data(self):
    """ Test Convert one SVG Image with an image with the data
        at the url of the image tag.ie:
         <image xlink:href="data:...." >
    """
    self._testImageConversionFromSVGToPNG("Web Page")

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
  def test_ImageConversionFromSVGToPNG_broken_url(self):
    """ Test Convert one SVG Image with an broken image href
    """
    self._testImageConversionFromSVGToPNG_broken_url("Image")

  def test_FileConversionFromSVGToPNG_broken_url(self):
    """ Test Convert one SVG Image with an broken image href
    """
    self._testImageConversionFromSVGToPNG_broken_url("File")

  def test_WebPageConversionFromSVGToPNG_broken_url(self):
    """ Test Convert one SVG Image with an broken image href
    """
    self._testImageConversionFromSVGToPNG_broken_url("Web Page")

  def test_ImageConversionFromSVGToPNG_empty_file(self):
    """ Test Convert one SVG Image with an empty svg
    """
    self._testImageConversionFromSVGToPNG_empty_file("Image")

  def test_FileConversionFromSVGToPNG_empty_file(self):
    """ Test Convert one SVG Image with an empty svg
    """
    self._testImageConversionFromSVGToPNG_empty_file("File")

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
  def test_ImageConversionFromSVGToPNG_file_url(self):
    """ Test Convert one SVG Image with an image using local path (file)
        at the url of the image tag. ie:
         <image xlink:href="file:///../../user-XXX-XXX"

        This is not used by ERP5 in production, but this is way that
        prooves that conversion from SVG to PNG can use external images.
    """
    self._testImageConversionFromSVGToPNG_file_url("Image")

  def test_FileConversionFromSVGToPNG_file_url(self):
    """ Test Convert one SVG Image with an image using local path (file)
        at the url of the image tag. ie:
         <image xlink:href="file:///../../user-XXX-XXX"

        This is not used by ERP5 in production, but this is way that
        prooves that conversion from SVG to PNG can use external images.
    """
    self._testImageConversionFromSVGToPNG_file_url("File")

  def test_WebPageConversionFromSVGToPNG_file_url(self):
    """ Test Convert one SVG Image with an image using local path (file)
        at the url of the image tag. ie:
         <image xlink:href="file:///../../user-XXX-XXX"

        This is not used by ERP5 in production, but this is way that
        prooves that conversion from SVG to PNG can use external images.
    """
    self._testImageConversionFromSVGToPNG_file_url("Web Page")

  def test_ImageConversionFromSVGToPNG_http_url(self):
    """ Test Convert one SVG Image with an image with a full
        url at the url of the image tag. ie:
         <image xlink:href="http://www.erp5.com/user-XXX-XXX"
    """
1101
    self._testImageConversionFromSVGToPNG_http_url("Image")
1102 1103 1104 1105 1106 1107

  def test_FileConversionFromSVGToPNG_http_url(self):
    """ Test Convert one SVG Image with an image with a full
        url at the url of the image tag. ie:
         <image xlink:href="http://www.erp5.com/user-XXX-XXX"
    """
1108
    self._testImageConversionFromSVGToPNG_http_url("File")
1109 1110 1111 1112 1113 1114

  def test_WebPageConversionFromSVGToPNG_http_url(self):
    """ Test Convert one SVG Image with an image with a full
        url at the url of the image tag. ie:
         <image xlink:href="http://www.erp5.com/user-XXX-XXX"
    """
1115
    self._testImageConversionFromSVGToPNG_http_url("Web Page")
1116

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
  def test_WebPageAsEmbeddedHtml_simplePage(self):
    """Test convert one simple html page to embedded html file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    html_data = "<p>World</p>"
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content=html_data)
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertEqual(ehtml_data, html_data)

  def test_WebPageAsMhtml_simplePage(self):
    """Test convert one simple html page to mhtml file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    title = "Hello"
    html_data = "<p>World</p>"
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(title=title, text_content=html_data)
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
    self.assertEqual(message.get_params(), [
      ("multipart/related", ""),
      ("type", "text/html"),
      ("boundary", message.get_boundary()),
    ])
    self.assertEqual(message.get("Subject"), title)
    htmlmessage, = message.get_payload()
    self.assertEqual(  # should have only one content transfer encoding header
      len([h for h in htmlmessage.keys() if h == "Content-Transfer-Encoding"]),
      1,
    )
    self.assertEqual(
      htmlmessage.get("Content-Transfer-Encoding"),
      "quoted-printable",
    )
    self.assertEqual(htmlmessage.get("Content-Location"), page.absolute_url())
    self.assertEqual(quopri.decodestring(htmlmessage.get_payload()), html_data)

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
  def test_WebPageAsEmbeddedHtml_pageWithLink(self):
    """Test convert one html page with links to embedded html file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content="".join([
      "<p>Hello</p>",
      '<a href="//a.a/">aa</a>',
      '<a href="/b">bb</a>',
      '<a href="c">cc</a>',
    ]))
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertEqual(ehtml_data, "".join([
      "<p>Hello</p>",
      '<a href="%s//a.a/">aa</a>' % self.portal.absolute_url().split("/", 1)[0],
      '<a href="%s/b">bb</a>' % self.portal.absolute_url(),
      '<a href="%s/c">cc</a>' % page.absolute_url(),
    ]))
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html", base_url="https://hel.lo/world/dummy")
    self.assertEqual(ehtml_data, "".join([
      "<p>Hello</p>",
      '<a href="https://a.a/">aa</a>',
      '<a href="https://hel.lo/b">bb</a>',
      '<a href="https://hel.lo/world/c">cc</a>',
    ]))

  def test_WebPageAsMhtml_pageWithLink(self):
    """Test convert one html page with links to mhtml file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    title = "Hello"
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(title=title, text_content="".join([
      "<p>Hello</p>",
      '<a href="//a.a/">aa</a>',
      '<a href="/b">bb</a>',
      '<a href="c">cc</a>',
    ]))
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
    htmlmessage, = message.get_payload()
    self.assertEqual(  # should have only one content transfer encoding header
      len([h for h in htmlmessage.keys() if h == "Content-Transfer-Encoding"]),
      1,
    )
    self.assertEqual(
      htmlmessage.get("Content-Transfer-Encoding"),
      "quoted-printable",
    )
    self.assertEqual(htmlmessage.get("Content-Location"), page.absolute_url())
    self.assertEqual(quopri.decodestring(htmlmessage.get_payload()), "".join([
      "<p>Hello</p>",
      '<a href="%s//a.a/">aa</a>' % self.portal.absolute_url().split("/", 1)[0],
      '<a href="%s/b">bb</a>' % self.portal.absolute_url(),
      '<a href="%s/c">cc</a>' % page.absolute_url(),
    ]))
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml", base_url="https://hel.lo/world/dummy")
    message = EmailParser().parsestr(mhtml_data)
    htmlmessage, = message.get_payload()
    self.assertEqual(htmlmessage.get("Content-Location"), "https://hel.lo/world")
    self.assertEqual(quopri.decodestring(htmlmessage.get_payload()), "".join([
      "<p>Hello</p>",
      '<a href="https://a.a/">aa</a>',
      '<a href="https://hel.lo/b">bb</a>',
      '<a href="https://hel.lo/world/c">cc</a>',
    ]))

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  def test_WebPageAsEmbeddedHtml_pageWithScript(self):
    """Test convert one html page with script to embedded html file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    html_data = "<script>alert('Hello');</script><p>World</p>"
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content=html_data)
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertEqual(ehtml_data, "<p>World</p>")

  def test_WebPageAsMhtml_pageWithScript(self):
    """Test convert one html page with script to mhtml file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    title = "Hello"
    html_data = "<script>alert('Hello');</script><p>World</p>"
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(title=title, text_content=html_data)
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
    htmlmessage, = message.get_payload()
    self.assertEqual(  # should have only one content transfer encoding header
      len([h for h in htmlmessage.keys() if h == "Content-Transfer-Encoding"]),
      1,
    )
    self.assertEqual(
      htmlmessage.get("Content-Transfer-Encoding"),
      "quoted-printable",
    )
    self.assertEqual(htmlmessage.get("Content-Location"), page.absolute_url())
    self.assertEqual(quopri.decodestring(htmlmessage.get_payload()), "<p>World</p>")

  def test_WebPageAsEmbeddedHtml_pageWithMoreThanOneImage(self):
    """Test convert one html page with images to embedded html file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    svg = image_module.newContent(portal_type="Image")
    svg.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
    svg.publish()
    png = image_module.newContent(portal_type="Image")
    png.edit(content_type="image/png", data=XSMALL_PNG_IMAGE_ICON_DATA)
    png.publish()
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content="".join([
      "<p>Hello</p>",
      '<img src="/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="/%s?format=" />' % png.getRelativeUrl(),
      '<img src="/%s?format=png" />' % svg.getRelativeUrl(),
    ]))
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertTrue(ehtml_data.startswith("".join([
      "<p>Hello</p>",
      '<img src="data:image/svg+xml;base64,%s" />' % b64encode(XSMALL_SVG_IMAGE_ICON_DATA),
      '<img src="data:image/png;base64,%s" />' % b64encode(XSMALL_PNG_IMAGE_ICON_DATA),
      '<img src="data:image/png;base64,'
    ])))

  def test_WebPageAsMhtml_pageWithMoreThanOneImage(self):
    """Test convert one html page with images to mhtml file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    svg = image_module.newContent(portal_type="Image")
    svg.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
    svg.publish()
    png = image_module.newContent(portal_type="Image")
    png.edit(content_type="image/png", data=XSMALL_PNG_IMAGE_ICON_DATA)
    png.publish()
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content="".join([
      "<p>Hello</p>",
      '<img src="/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="/%s?format=" />' % png.getRelativeUrl(),
      '<img src="/%s?format=png" />' % svg.getRelativeUrl(),
    ]))
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
    htmlmessage, svgmessage, pngmessage, svgtopngmessage = message.get_payload()
    self.assertEqual(
      quopri.decodestring(htmlmessage.get_payload()),
      "".join([
        "<p>Hello</p>",
        '<img src="%s?format=" />' % svg.absolute_url(),
        '<img src="%s?format=" />' % png.absolute_url(),
        '<img src="%s?format=png" />' % svg.absolute_url(),
      ]),
    )
    for content_type, ext, message, obj, data in [
          ("image/svg+xml", "", svgmessage, svg, XSMALL_SVG_IMAGE_ICON_DATA),
          ("image/png", "", pngmessage, png, XSMALL_PNG_IMAGE_ICON_DATA),
          ("image/png", "png", svgtopngmessage, svg, None),
        ]:
1323
      __traceback_info__ = (content_type, "?format=" + ext) # pylint: disable=unused-variable
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
      self.assertEqual(
        message.get("Content-Location"),
        obj.absolute_url() + "?format=" + ext,
      )
      self.assertEqual(  # should have only one content transfer encoding header
        len([h for h in message.keys() if h == "Content-Transfer-Encoding"]),
        1,
      )
      self.assertEqual(message.get("Content-Type"), content_type)
      encoding = message.get("Content-Transfer-Encoding")
      self.assertIn(encoding, ("base64", "quoted-printable"))
      # quoted printable encoding is accepted for svg images
      if data:
        if encoding == "base64":
          self.assertEqual(
            b64decode(message.get_payload()),
            data,
          )
        elif encoding == "quoted-printable":
          self.assertEqual(
            quopri.decodestring(message.get_payload()),
            data,
          )
        else:
          raise ValueError("unhandled encoding %r" % encoding)
      else:
        self.assertTrue(len(message.get_payload()) > 0)

  @customScript("ERP5Site_getWebSiteDomainDict", "", 'return {"test.portal.erp": context.getPortalObject()}')
  def test_WebPageAsEmbeddedHtml_pageWithDifferentHref(self):
    """Test convert one html page with images to embedded html file"""
    # Test init part
    # XXX use web site domain properties instead of @customScript
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    svg = image_module.newContent(portal_type="Image")
    svg.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
    svg.publish()
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content="".join([
      "<p>Hello</p>",
      '<img src="%s?format=" />' % svg.getRelativeUrl(),
1366
      '<img src="%s?display=" />' % svg.getRelativeUrl(),
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
      '<img src="/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="//test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="http://test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="https://test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="//example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="http://example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="https://example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="data:image/svg+xml,&lt;svg&gt;&lt;/svg&gt;" />',
      '<img src="tel:1234567890" />',
      '<img src="mailto:me" />',
    ]))
    protocol = page.absolute_url().split(":", 1)[0] + ":"
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertEqual(ehtml_data, "".join([
      "<p>Hello</p>",
    ] + ([
      '<img src="data:image/svg+xml;base64,%s" />' % b64encode(XSMALL_SVG_IMAGE_ICON_DATA),
1385
    ] * 6) + [
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
      '<img src="%s//example.com/%s?format=" />' % (protocol, svg.getRelativeUrl()),
      '<img src="http://example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="https://example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="data:image/svg+xml,&lt;svg&gt;&lt;/svg&gt;" />',
      '<img src="tel:1234567890" />',
      '<img src="mailto:me" />',
    ]))

  @customScript("ERP5Site_getWebSiteDomainDict", "", 'return {"test.portal.erp": context.getPortalObject()}')
  def test_WebPageAsMhtml_pageWithDifferentHref(self):
    """Test convert one html page with images to mhtml file"""
    # Test init part
    # XXX use web site domain properties instead of @customScript
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    svg = image_module.newContent(portal_type="Image")
    svg.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
    svg.publish()
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(text_content="".join([
      "<p>Hello</p>",
      '<img src="%s?format=" />' % svg.getRelativeUrl(),
1408
      '<img src="%s?display=" />' % svg.getRelativeUrl(),
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
      '<img src="/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="//test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="http://test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="https://test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="//example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="http://example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="https://example.com/%s?format=" />' % svg.getRelativeUrl(),
      '<img src="data:image/svg+xml,&lt;svg&gt;&lt;/svg&gt;" />',
      '<img src="tel:1234567890" />',
      '<img src="mailto:me" />',
    ]))
    protocol = page.absolute_url().split(":", 1)[0] + ":"
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
1424
    self.assertEqual(len(message.get_payload()), 7)
1425 1426 1427 1428 1429 1430
    htmlmessage = message.get_payload()[0]
    self.assertEqual(
      quopri.decodestring(htmlmessage.get_payload()),
      "".join([
        "<p>Hello</p>",
        '<img src="%s/%s?format=" />' % (page.absolute_url(), svg.getRelativeUrl()),
1431
        '<img src="%s/%s?display=" />' % (page.absolute_url(), svg.getRelativeUrl()),
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        '<img src="%s?format=" />' % svg.absolute_url(),
        '<img src="%s//test.portal.erp/%s?format=" />' % (protocol, svg.getRelativeUrl()),
        '<img src="http://test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
        '<img src="https://test.portal.erp/%s?format=" />' % svg.getRelativeUrl(),
        '<img src="%s//example.com/%s?format=" />' % (protocol, svg.getRelativeUrl()),
        '<img src="http://example.com/%s?format=" />' % svg.getRelativeUrl(),
        '<img src="https://example.com/%s?format=" />' % svg.getRelativeUrl(),
        '<img src="data:image/svg+xml,&lt;svg&gt;&lt;/svg&gt;" />',
        '<img src="tel:1234567890" />',
        '<img src="mailto:me" />',
      ]),
    )
    for message, location in [
          (message.get_payload()[1], "%s/%s?format=" % (page.absolute_url(), svg.getRelativeUrl())),
1446 1447 1448 1449 1450
          (message.get_payload()[2], "%s/%s?display=" % (page.absolute_url(), svg.getRelativeUrl())),
          (message.get_payload()[3], "%s?format=" % svg.absolute_url()),
          (message.get_payload()[4], "%s//test.portal.erp/%s?format=" % (protocol, svg.getRelativeUrl())),
          (message.get_payload()[5], "http://test.portal.erp/%s?format=" % svg.getRelativeUrl()),
          (message.get_payload()[6], "https://test.portal.erp/%s?format=" % svg.getRelativeUrl()),
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
        ]:
      self.assertEqual(
        message.get("Content-Location"),
        location,
      )
      self.assertEqual(  # should have only one content transfer encoding header
        len([h for h in message.keys() if h == "Content-Transfer-Encoding"]),
        1,
      )
      encoding = message.get("Content-Transfer-Encoding")
      self.assertIn(encoding, ("base64", "quoted-printable"))
      # quoted printable encoding is accepted for svg images
      if encoding == "base64":
        self.assertEqual(
          b64decode(message.get_payload()),
          XSMALL_SVG_IMAGE_ICON_DATA,
        )
      elif encoding == "quoted-printable":
        self.assertEqual(
          quopri.decodestring(message.get_payload()),
          XSMALL_SVG_IMAGE_ICON_DATA,
        )
      else:
        raise ValueError("unhandled encoding %r" % encoding)

  def test_WebPageAsEmbeddedHtml_pageWith1000Image(self):
    """Test convert one html page with 1000 images to embedded html file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    page = web_page_module.newContent(portal_type="Web Page")
    text_content_list = ["<p>Hello</p>"]
1483
    for _ in range(0, 1000, 5):
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
      svg = image_module.newContent(portal_type="Image")
      svg.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
      svg.publish()
      png = image_module.newContent(portal_type="Image")
      png.edit(content_type="image/png", data=XSMALL_PNG_IMAGE_ICON_DATA)
      png.publish()
      text_content_list += [
        '<img src="/%s?format=" />' % svg.getRelativeUrl(),
        '<img src="/%s?format=" />' % png.getRelativeUrl(),
        '<img src="/%s?format=png" />' % svg.getRelativeUrl(),
        '<img src="/%s?format=jpg" />' % png.getRelativeUrl(),
        '<img src="/%s?format=jpg" />' % svg.getRelativeUrl(),
      ]
    page.edit(text_content="".join(text_content_list))
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertEqual(ehtml_data.count("<img"), 1000)

  def test_WebPageAsMhtml_pageWith1000Image(self):
    """Test convert one html page with 1000 images to mhtml file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    page = web_page_module.newContent(portal_type="Web Page")
    text_content_list = ["<p>Hello</p>"]
1509
    for _ in range(0, 1000, 5):
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
      svg = image_module.newContent(portal_type="Image")
      svg.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
      svg.publish()
      png = image_module.newContent(portal_type="Image")
      png.edit(content_type="image/png", data=XSMALL_PNG_IMAGE_ICON_DATA)
      png.publish()
      text_content_list += [
        '<img src="/%s?format=" />' % svg.getRelativeUrl(),
        '<img src="/%s?format=" />' % png.getRelativeUrl(),
        '<img src="/%s?format=png" />' % svg.getRelativeUrl(),
        '<img src="/%s?format=jpg" />' % png.getRelativeUrl(),
        '<img src="/%s?format=jpg" />' % svg.getRelativeUrl(),
      ]
    page.edit(text_content="".join(text_content_list))
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
    self.assertEqual(len(message.get_payload()), 1001)

  def test_WebPageAsEmbeddedHtml_pageWithStyle(self):
    """Test convert one html page with style tag to embedded html file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    img = image_module.newContent(portal_type="Image")
    img.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
    img.publish()
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(
      text_content="<style>%s</style><p>Hello</p>" % (
        'body { background-image: url(  "/%s?format=" ); }' % (
          img.getRelativeUrl())),
    )
    # Test part
    ehtml_data = page.WebPage_exportAsSingleFile(format="embedded_html")
    self.assertEqual(
      ehtml_data,
      "<style>%s</style><p>Hello</p>" % (
        'body { background-image: url(data:image/svg+xml;base64,%s); }' % (
          b64encode(XSMALL_SVG_IMAGE_ICON_DATA))),
    )

  def test_WebPageAsMhtml_pageWithStyle(self):
    """Test convert one html page with style tag to mhtml file"""
    # Test init part
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    img = image_module.newContent(portal_type="Image")
    img.edit(content_type="image/svg+xml", data=XSMALL_SVG_IMAGE_ICON_DATA)
    img.publish()
    page = web_page_module.newContent(portal_type="Web Page")
    page.edit(
      text_content="<style>%s</style><p>Hello</p>" % (
        'body { background-image: url(  "/%s?format=" ); }' % (
          img.getRelativeUrl())),
    )
    # Test part
    mhtml_data = page.WebPage_exportAsSingleFile(format="mhtml")
    message = EmailParser().parsestr(mhtml_data)
    htmlmessage, imagemessage = message.get_payload()
    self.assertEqual(
      quopri.decodestring(htmlmessage.get_payload()),
      "<style>%s</style><p>Hello</p>" % (
        "body { background-image: url(%s?format=); }" % (
          img.absolute_url())),
    )
    self.assertEqual(
      imagemessage.get("Content-Location"),
      img.absolute_url() + "?format=",
    )
    self.assertEqual(  # should have only one content transfer encoding header
      len([h for h in imagemessage.keys() if h == "Content-Transfer-Encoding"]),
      1,
    )
    encoding = imagemessage.get("Content-Transfer-Encoding")
    self.assertIn(encoding, ("base64", "quoted-printable"))
    # quoted printable encoding is accepted for svg images
    if encoding == "base64":
      self.assertEqual(
        b64decode(imagemessage.get_payload()),
        XSMALL_SVG_IMAGE_ICON_DATA,
      )
    elif encoding == "quoted-printable":
      self.assertEqual(
        quopri.decodestring(imagemessage.get_payload()),
        XSMALL_SVG_IMAGE_ICON_DATA,
      )
    else:
      raise ValueError("unhandled encoding %r" % encoding)

1600 1601 1602 1603 1604 1605 1606
  @customScript("ERP5Site_getWebSiteDomainDict", "", """return {
    "test.portal.erp": context.getPortalObject(),
    "test.site.erp": context.getPortalObject().web_site_module.test,
  }""")
  def test_WebPageImplicitSuccessorValueList(self):
    # Test init part
    # XXX use web site domain properties instead of @customScript
1607
    self.setupWebSite()
1608 1609 1610
    web_page_module = self.portal.getDefaultModule(portal_type="Web Page")
    image_module = self.portal.getDefaultModule(portal_type="Image")
    img_list = []
1611
    for i in range(14):
1612 1613 1614 1615 1616 1617 1618 1619 1620
      img = image_module.newContent(
        data=XSMALL_SVG_IMAGE_ICON_DATA,
        reference="P-IMG-implicit.successor.value.list.test.%d" % i,
        version="001",
        language="en",
      )
      img.publish()
      img_list.append(img)
    page = web_page_module.newContent(
1621
      portal_type="Web Page",
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
      reference="P-WP-implicit.successor.value.list.test",
      version="001",
      language="en",
      text_content="".join([
        "<p>Hello</p>",
        '<a href="%s" />' % img_list[0].getRelativeUrl(),
        '<a href="%s" />' % img_list[0].getRelativeUrl(),
        '<a href="./%s" />' % img_list[1].getRelativeUrl(),
        '<a href="/%s" />' % img_list[2].getRelativeUrl(),
        '<a href="%s/view" />' % img_list[3].getRelativeUrl(),
        '<a href="P-IMG-implicit.successor.value.list.test.4" />',
        '<a href="./P-IMG-implicit.successor.value.list.test.5" />',
        '<a href="./P-IMG-implicit.successor.value.list.test.6/view" />',
        '<a href="/P-IMG-implicit.successor.value.list.test.7/view" />',
        '<a href="//test.site.erp/P-IMG-implicit.successor.value.list.test.8/view" />',
        '<a href="http://test.site.erp/P-IMG-implicit.successor.value.list.test.9/view" />',
        '<img src="P-IMG-implicit.successor.value.list.test.10?format=" />',
        '<iframe src="/%s" />' % img_list[11].getRelativeUrl(),
        '<style>body { background-image: url("P-IMG-implicit.successor.value.list.test.12?format=png"); }</style>',
1641
        '<script src="P-IMG-implicit.successor.value.list.test.13" type="text/javascript"></script>',
1642 1643 1644 1645
      ]),
    )
    page.publish()
    self.tic()
1646

1647
    # Test part
1648
    self.maxDiff = None
1649 1650 1651 1652
    successor_list = self.portal.web_site_module.test\
      .restrictedTraverse("P-WP-implicit.successor.value.list.test")\
      .getImplicitSuccessorValueList()
    self.assertEqual(
1653 1654
      sorted([s.getReference() for s in successor_list]),
      sorted([i.getReference() for i in img_list]),
1655 1656
    )

1657 1658 1659 1660 1661 1662 1663 1664 1665
    # same with the web page retrieved with getDocumentValue
    successor_list = self.portal.web_site_module.test.getDocumentValue(
        "P-WP-implicit.successor.value.list.test"
    ).getImplicitSuccessorValueList()
    self.assertEqual(
      sorted([s.getReference() for s in successor_list]),
      sorted([i.getReference() for i in img_list]),
    )

1666
  def checkWebSiteDocumentViewConsistency(self, portal_type, module_id="document_module"):
1667
    """
1668 1669 1670
      Checks that the default view action of a <portal_type>, viewing from a web site,
      is `web_view`.
      (e.g. output of .../document_module/1/ differs if `web_view` visible or not)
1671
    """
1672
    portal = self.portal
1673
    web_site = self.setupWebSite()
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

    # extract script id from `web_view` action
    # Use `contentValues` because `searchFolder` does not find any web_view action.
    for action in portal.portal_types[portal_type].contentValues(portal_type="Action Information"):
      if action.getReference() == "web_view":
        break
    else:
      raise LookupError("No action with reference 'web_view' found")
    assert action.getVisible() is 1

1684
    # check when the file is empty
1685 1686
    document_object = portal[module_id].newContent(portal_type=portal_type)
    document_object.publish()
1687
    self.tic()
1688
    path = '%s/%s/%s/' % (
1689
      web_site.absolute_url_path(),
1690 1691
      module_id,
      document_object.getId())
1692
    response_a = self.publish(path)
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
    action.setVisible(0)
    self.tic()
    response_b = self.publish(path)
    self.assertNotEqual(response_a.getBody(), response_b.getBody())

  def test_checkWebSiteFileViewConsistency(self):
    """
      Checks that the default view action of a File, viewing from a web site,
      is `web_view`.
    """
    self.checkWebSiteDocumentViewConsistency("File")
1704 1705 1706 1707

  def test_checkWebSiteImageViewConsistency(self):
    """
      Checks that the default view action of a Image, viewing from a web site,
1708
      is `web_view`.
1709
    """
1710
    self.checkWebSiteDocumentViewConsistency("Image", module_id="image_module")
1711

1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
  def test_checkWebSiteTextViewConsistency(self):
    """
      Checks that the default view action of a Text, viewing from a web site,
      is `web_view`.
    """
    self.checkWebSiteDocumentViewConsistency("Text")

  def test_checkWebSitePresentationViewConsistency(self):
    """
      Checks that the default view action of a Presentation, viewing from a web
      site, is `web_view`.
    """
    self.checkWebSiteDocumentViewConsistency("Presentation")

  def test_checkWebSiteSpreadsheetViewConsistency(self):
    """
      Checks that the default view action of a Spreadsheet, viewing from a web
      site, is `web_view`.
    """
    self.checkWebSiteDocumentViewConsistency("Spreadsheet")

  def test_checkWebSiteDrawingViewConsistency(self):
    """
      Checks that the default view action of a Drawing, viewing from a web site,
      is `web_view`.
    """
    self.checkWebSiteDocumentViewConsistency("Drawing")

1740 1741 1742 1743
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5WebWithDms))
  return suite