示例#1
0
  def test_InvoiceViewAsODT(self):
    """Create ODT printout """
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',)
    client = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Client')
    vendor = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Vendor')
    invoice = self.portal.getDefaultModule(self.invoice_portal_type).newContent(
                              portal_type=self.invoice_portal_type,
                              specialise=self.business_process,
                              start_date=DateTime(2008, 12, 31),
                              title='Invoice',
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client)
    line = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=10,
                            price=3)
    invoice.confirm()
    self.tic()

    odt = invoice.Invoice_viewAsODT()
    from Products.ERP5OOo.tests.utils import Validator
    odf_validator = Validator()
    err_list = odf_validator.validate(odt)
    if err_list:
      self.fail(''.join(err_list))
示例#2
0
  def afterSetUp(self):
    self.login()
    self.getPortal().Localizer = DummyLocalizer()
    v12schema_url = os.path.join(os.path.dirname(__file__),
                                 'OpenDocument-v1.2-os-schema.rng')
    self.validator = Validator(schema_url=v12schema_url)
    en_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_en.odt')
    en_file = open(en_file_path, 'rb')
    ja_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_ja.odt')
    ja_file = open(ja_file_path, 'rb')

    addStyleSheet = self.getPortal().manage_addProduct['OFSP'].manage_addFile
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_en', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_en', file=en_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_ja', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_ja', file=ja_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Base_getODTStyleSheetByLanguage', None) is None:
      script_body = """
current_language = context.Localizer.get_selected_language()
return getattr(context, "%s_%s" % (parameter, current_language))
"""
      dispatcher = self.getPortal().manage_addProduct['PythonScripts']
      dispatcher.manage_addPythonScript('Base_getODTStyleSheetByLanguage')
      script = self.getPortal().Base_getODTStyleSheetByLanguage
      script.ZPythonScript_edit('parameter', script_body)
示例#3
0
  def test_InvoiceViewAsODT(self):
    """Create ODT printout """
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',)
    client = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Client')
    vendor = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Vendor')
    invoice = self.portal.getDefaultModule(self.invoice_portal_type).newContent(
                              portal_type=self.invoice_portal_type,
                              specialise=self.business_process,
                              start_date=DateTime(2008, 12, 31),
                              title='Invoice',
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client)
    line = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=10,
                            price=3)
    invoice.confirm()
    self.tic()

    odt = invoice.Invoice_viewAsODT()
    from Products.ERP5OOo.tests.utils import Validator
    odf_validator = Validator()
    err_list = odf_validator.validate(odt)
    if err_list:
      self.fail(''.join(err_list))
示例#4
0
  def afterSetUp(self):
    if not self.skin:
      raise NotImplementedError('Subclasses must define skin')

    gender = self.portal.portal_categories.gender
    if 'male' not in gender.objectIds():
      gender.newContent(id='male')
      self.portal.portal_caches.clearAllCache()

    self.auth = 'ERP5TypeTestCase:'
    person_module = self.portal.person_module
    if person_module._getOb('pers', None) is None:
      person_module.newContent(id='pers', portal_type='Person')
      self.tic()
    person_module.pers.setFirstName('Bob')
    person_module.pers.setGender(None)
    person_module.pers.setCareerRole(None)

    if person_module.pers._getOb('img', None) is None:
      person_module.pers.newContent(portal_type='Embedded File', id='img')

    if person_module._getOb('pers_without_image', None) is None:
      person = person_module.newContent(
                              portal_type='Person',
                              id = 'pers_without_image',
                              first_name = 'Test')
      self.tic()

    self.portal.changeSkin(self.skin)
    self.validator = Validator()
    # make sure selections are empty
    name = 'person_module_selection'
    self.portal.portal_selections.setSelectionFor(name, Selection(name))
示例#5
0
    def afterSetUp(self):
        self.auth = 'ERP5TypeTestCase:'
        portal = self.getPortal()
        container = portal.portal_skins.custom
        if self.form_id not in container.objectIds():
            container.manage_addProduct['ERP5Form'].addERP5Form(
                self.form_id, 'View')
            form = getattr(container, self.form_id)

            # create some persons in person_module
            self.createPersons()
            # add a ListBox field
            form.manage_addField('listbox', 'listbox', 'ListBox')
            form.listbox.ListBox_setPropertyList(
                field_list_method='zCountDocumentPerOwner',
                field_count_method='',
                field_columns=[
                    'owner | Owner', 'owner_count | Owner Count',
                    'number_count | Reference Count'
                ],
            )

            # create a Field OOoChart
            form.manage_addField(self.ooo_chart_id, self.ooo_chart_id,
                                 'OOoChart')

            # create a Field OOoChart
            form.manage_addField('your_ooochart', 'your_ooochart', 'OOoChart')

            # create a ZSQL Method
            sql = """SELECT owner, count(uid) AS owner_count,
              count(reference) AS number_count
              FROM catalog
              WHERE portal_type = 'Person'
              GROUP BY owner ORDER BY owner_count DESC"""

            template = String(source_string=sql)
            container.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
                'zCountDocumentPerOwner', 'zCountDocumentPerOwner',
                'erp5_sql_connection', '', template)
            # enable preference
            preference = self.getPortal(
            ).portal_preferences.default_site_preference
            preference.setPriority(1)
            if preference.getPreferenceState() == 'disabled':
                self.getWorkflowTool().doActionFor(ob=preference,
                                                   action='enable_action',
                                                   wf_id='preference_workflow')

        self.validator = Validator()
        self.tic()
示例#6
0
 def test_normal_form(self):
     self.loginAsUser('bob')
     # simulate a big request, for which Base_callDialogMethod will not issue a
     # redirect
     response = self.publish(
         '/%s/person_module/pers/Base_callDialogMethod?deferred_portal_skin=%s&'
         'dialog_method=Person_view&dialog_id=Person_view&'
         'deferred_style:int=1&junk=%s' %
         (self.portal.getId(), self.skin, 'X' * 2000),
         '%s:%s' % (self.username, self.password))
     self.tic()
     last_message = self.portal.MailHost._last_message
     self.assertNotEquals((), last_message)
     mfrom, mto, message_text = last_message
     self.assertEqual(
         '"%s" <%s>' % (self.first_name, self.recipient_email_address),
         mto[0])
     mail_message = email.message_from_string(message_text)
     for part in mail_message.walk():
         content_type = part.get_content_type()
         if content_type == self.content_type:
             # "Person" is the title of Person_view form
             file_name = part.get_filename()
             expected_file_name = 'Person%s' % self.attachment_file_extension
             self.assertEqual(expected_file_name, file_name)
             self.assertEqual(
                 'attachment; filename="%s"' % expected_file_name,
                 part.get('Content-Disposition'))
             data = part.get_payload(decode=True)
             error_list = Validator().validate(data)
             if error_list:
                 self.fail(''.join(error_list))
             break
     else:
         self.fail('Attachment not found in email\n%s' % message_text)
示例#7
0
 def test_report_view(self):
     self.loginAsUser('bob')
     self.portal.changeSkin('Deferred')
     response = self.publish(
         '/%s/person_module/pers/Base_viewHistory?deferred_portal_skin=%s' %
         (self.portal.getId(), self.skin),
         '%s:%s' % (self.username, self.password))
     self.tic()
     last_message = self.portal.MailHost._last_message
     self.assertNotEquals((), last_message)
     mfrom, mto, message_text = last_message
     self.assertEqual(
         '"%s" <%s>' % (self.first_name, self.recipient_email_address),
         mto[0])
     mail_message = email.message_from_string(message_text)
     for part in mail_message.walk():
         content_type = part.get_content_type()
         file_name = part.get_filename()
         if content_type == self.content_type:
             # "History" is the title of Base_viewHistory form
             file_name = part.get_filename()
             expected_file_name = 'History%s' % self.attachment_file_extension
             self.assertEqual(expected_file_name, file_name)
             self.assertEqual(
                 'attachment; filename="%s"' % expected_file_name,
                 part.get('Content-Disposition'))
             data = part.get_payload(decode=True)
             error_list = Validator().validate(data)
             if error_list:
                 self.fail(''.join(error_list))
             break
     else:
         self.fail('Attachment not found in email\n%s' % message_text)
示例#8
0
  def afterSetUp(self):
    self.login()
    self.getPortal().Localizer = DummyLocalizer()
    v12schema_url = os.path.join(os.path.dirname(__file__),
                                 'OpenDocument-v1.2-os-schema.rng') 
    self.validator = Validator(schema_url=v12schema_url)
    en_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_en.odt')
    en_file = open(en_file_path, 'rb')
    ja_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_ja.odt')
    ja_file = open(ja_file_path, 'rb')

    addStyleSheet = self.getPortal().manage_addProduct['OFSP'].manage_addFile
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_en', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_en', file=en_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_ja', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_ja', file=ja_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Base_getODTStyleSheetByLanguage', None) is None:
      script_body = """
current_language = context.Localizer.get_selected_language()
return getattr(context, "%s_%s" % (parameter, current_language))
"""
      dispatcher = self.getPortal().manage_addProduct['PythonScripts']
      dispatcher.manage_addPythonScript('Base_getODTStyleSheetByLanguage')
      script = self.getPortal().Base_getODTStyleSheetByLanguage
      script.ZPythonScript_edit('parameter', script_body)
示例#9
0
  def afterSetUp(self):
    if not self.skin:
      raise NotImplementedError('Subclasses must define skin')

    self.setDefaultSitePreference()

    gender = self.portal.portal_categories.gender
    if 'male' not in gender.objectIds():
      gender.newContent(id='male')
      self.portal.portal_caches.clearAllCache()

    self.auth = 'ERP5TypeTestCase:'
    person_module = self.portal.person_module
    if person_module._getOb('pers', None) is None:
      person_module.newContent(id='pers', portal_type='Person')
      self.tic()
    person_module.pers.setFirstName('Bob')
    person_module.pers.setGender(None)
    person_module.pers.setCareerRole(None)

    if person_module.pers._getOb('img', None) is None:
      person_module.pers.newContent(portal_type='Embedded File', id='img')

    if person_module._getOb('pers_without_image', None) is None:
      person = person_module.newContent(
                              portal_type='Person',
                              id = 'pers_without_image',
                              first_name = 'Test')
      self.tic()

    self.portal.changeSkin(self.skin)
    self.validator = Validator()
    # make sure selections are empty
    name = 'person_module_selection'
    self.portal.portal_selections.setSelectionFor(name, Selection(name))
示例#10
0
    def afterSetUp(self):
        self.login()
        self.setSystemPreference()
        # XML validator
        v12schema_url = os.path.join(os.path.dirname(__file__),
                                     'OpenDocument-v1.2-os-schema.rng')
        self.validator = Validator(schema_url=v12schema_url)

        foo_file_path = os.path.join(os.path.dirname(__file__),
                                     'test_document', 'Foo_001.odg')
        foo_file = open(foo_file_path, 'rb')
        self._validate(foo_file.read())
        custom = self.portal.portal_skins.custom
        addStyleSheet = custom.manage_addProduct['OFSP'].manage_addFile
        if custom._getOb('Foo_getODGStyleSheet', None) is None:
            addStyleSheet(
                id='Foo_getODGStyleSheet',
                file=foo_file,
                title='',
                precondition='',
                content_type='application/vnd.oasis.opendocument.graphics')
        erp5OOo = custom.manage_addProduct['ERP5OOo']

        if custom._getOb('Foo_viewAsODGPrintout', None) is None:
            erp5OOo.addFormPrintout(id='Foo_viewAsODGPrintout',
                                    title='',
                                    form_name='Foo_view',
                                    template='Foo_getODGStyleSheet')
        if custom._getOb('Foo_viewProxyFieldAsODGPrintout', None) is None:
            erp5OOo.addFormPrintout(id='Foo_viewProxyFieldAsODGPrintout',
                                    title='',
                                    form_name='Foo_viewProxyField',
                                    template='Foo_getODGStyleSheet')
        if custom._getOb('FooReport_viewAsODGPrintout', None) is None:
            erp5OOo.addFormPrintout(id='FooReport_viewAsODGPrintout', title='')

        ## append 'test1' data to a listbox
        foo_module = self.portal.foo_module
        if foo_module._getOb('test1', None) is None:
            foo_module.newContent(id='test1', portal_type='Foo')
        test1 = foo_module.test1
        if test1._getOb("foo_1", None) is None:
            test1.newContent("foo_1",
                             title='Foo Line 1',
                             portal_type='Foo Line')
        if test1._getOb("foo_2", None) is None:
            test1.newContent("foo_2",
                             title='Foo Line 2',
                             portal_type='Foo Line')
        self.tic()
示例#11
0
    def afterSetUp(self):
      self.auth = 'ERP5TypeTestCase:'
      portal = self.getPortal()
      container = portal.portal_skins.custom
      if self.form_id not in container.objectIds():
        container._setObject(self.form_id, ERP5Form(self.form_id, 'View'))
        form = getattr(container, self.form_id)

        # create some persons in person_module
        self.createPersons()
        # add a ListBox field
        form.manage_addField('listbox', 'listbox', 'ListBox')
        form.listbox.ListBox_setPropertyList(field_list_method='zCountDocumentPerOwner',
                                field_count_method='',
                                field_columns=['owner | Owner',
                                              'owner_count | Owner Count',
                                              'number_count | Reference Count'],
                                )

        # create a Field OOoChart
        form.manage_addField(self.ooo_chart_id, self.ooo_chart_id, 'OOoChart')
        
        # create a Field OOoChart
        form.manage_addField('your_ooochart', 'your_ooochart', 'OOoChart')



        # create a ZSQL Method
        sql = """SELECT owner, count(uid) AS owner_count,
                count(reference) AS number_count
                FROM catalog
                WHERE portal_type = 'Person'
                GROUP BY owner ORDER BY owner_count DESC"""

        template = String(source_string=sql)
        container.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod('zCountDocumentPerOwner', 'zCountDocumentPerOwner', 'erp5_sql_connection', '', template)
        # enable preference
        preference = self.getPortal().portal_preferences.default_site_preference
        preference.setPriority(1)
        if preference.getPreferenceState() == 'disabled':
          self.getWorkflowTool().doActionFor(ob=preference,
                                            action='enable_action',
                                            wf_id='preference_workflow')

      self.validator = Validator()
      transaction.commit()
      self.tic()
示例#12
0
class TestOooDynamicStyle(ERP5TypeTestCase):
  manager_username = '******'
  manager_password = '******'
  content_type_writer = 'application/vnd.oasis.opendocument.text'
  content = "<office:document-content xmlns:draw='urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0' xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0' xmlns:ooo='http://openoffice.org/2004/office' xmlns:number='urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0' xmlns:table='urn:oasis:names:tc:opendocument:xmlns:table:1.0' xmlns:dr3d='urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0' xmlns:fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0' xmlns:style='urn:oasis:names:tc:opendocument:xmlns:style:1.0' xmlns:xforms='http://www.w3.org/2002/xforms' xmlns:form='urn:oasis:names:tc:opendocument:xmlns:form:1.0' xmlns:script='urn:oasis:names:tc:opendocument:xmlns:script:1.0' xmlns:ooow='http://openoffice.org/2004/writer' xmlns:svg='urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0' xmlns:chart='urn:oasis:names:tc:opendocument:xmlns:chart:1.0' xmlns:dom='http://www.w3.org/2001/xml-events' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:oooc='http://openoffice.org/2004/calc' xmlns:math='http://www.w3.org/1998/Math/MathML' xmlns:tal='http://xml.zope.org/namespaces/tal' office:version='1.2'><office:scripts /><office:font-face-decls /><office:automatic-styles /><office:body><office:text /></office:body></office:document-content>"

  def getTitle(self):
    return "TestOOoDynamicStyle"

  def getBusinessTemplateList(self):
    return ('erp5_core_proxy_field_legacy',
            'erp5_full_text_myisam_catalog',
            'erp5_base',
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_ingestion',
            'erp5_web', 
            'erp5_dms')


  def afterSetUp(self):
    self.login()
    self.getPortal().Localizer = DummyLocalizer()
    v12schema_url = os.path.join(os.path.dirname(__file__),
                                 'OpenDocument-v1.2-os-schema.rng') 
    self.validator = Validator(schema_url=v12schema_url)
    en_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_en.odt')
    en_file = open(en_file_path, 'rb')
    ja_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_ja.odt')
    ja_file = open(ja_file_path, 'rb')

    addStyleSheet = self.getPortal().manage_addProduct['OFSP'].manage_addFile
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_en', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_en', file=en_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_ja', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_ja', file=ja_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Base_getODTStyleSheetByLanguage', None) is None:
      script_body = """
current_language = context.Localizer.get_selected_language()
return getattr(context, "%s_%s" % (parameter, current_language))
"""
      dispatcher = self.getPortal().manage_addProduct['PythonScripts']
      dispatcher.manage_addPythonScript('Base_getODTStyleSheetByLanguage')
      script = self.getPortal().Base_getODTStyleSheetByLanguage
      script.ZPythonScript_edit('parameter', script_body)

  def _validate(self, odf_file_data):
    error_list = self.validator.validate(odf_file_data)
    if error_list:
      self.fail(''.join(error_list))

  def test_01_dynamic(self):
    """
    Test applying stylesheet dynamically, using a Python Script with
    a stylesheet file name parameter.
    """
    request = self.app.REQUEST
    addOOoTemplate = self.getPortal().manage_addProduct['ERP5OOo'].addOOoTemplate
    addOOoTemplate(id='Dynamic_viewAsOdt', title='')
    Dynamic_viewAsOdt = self.getPortal().Dynamic_viewAsOdt
    # The stylesheet file 'Test_getODTStyleSheet' is not exist in this site.
    # So, the 'Base_getODTStyleSheet', a python script creates dynamically 
    # exsited stylesheet file name. 
    self.assertFalse(self.getPortal().hasObject('Test_getODTStyleSheet'))
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_ja'))
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_en'))
    Dynamic_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                 ooo_stylesheet='Test_getODTStyleSheet', 
                                 script_name='Base_getODTStyleSheetByLanguage')
    Dynamic_viewAsOdt.pt_edit(self.content, content_type='application/vnd.oasis.opendocument.text')

    # 1. test a normal case, language: ja
    self.getPortal().Localizer.changeLanguage('ja')
    response = self.publish('/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
    self.assertEqual('application/vnd.oasis.opendocument.text',
                     response.getHeader('content-type').split(';')[0])
    self.assertEqual('attachment; filename="Dynamic_viewAsOdt.odt"',
                     response.getHeader('content-disposition'))
    self._validate(response.getBody()) 
    self.assertTrue(200, response.getStatus())

    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(len(styles_xml_body) > 0)
    # 'Style sheet ja' text is in the odt document header, 
    # and the header is in the 'styles.xml'.
    self.assertTrue(styles_xml_body.find('Style sheet ja') > 0)

    # 2. test a normal case, change the language to 'en', 
    #    so that the stylesheet changes dynamically.
    self.getPortal().Localizer = DummyLocalizer()
    self.getPortal().Localizer.changeLanguage('en')
    response = self.publish('/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
    self._validate(response.getBody()) 
    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(styles_xml_body.find('Style sheet en') > 0)

    # 3. test a fail case, reset a not existed stylesheet
    Dynamic_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                 ooo_stylesheet='NotFound_getODTStyleSheet', 
                                 script_name='Base_getODTStyleSheet')
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet'))
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet_ja'))
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet_en'))
    self.getPortal().Localizer.changeLanguage('en')
    response = self.publish('/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
    # then, it is not a zip stream 
    self.assertFalse(response.getBody().startswith('PK'))
    self.assertTrue(500, response.getStatus())
   

  def test_02_static(self):
    """
    Test applying stylesheet statically, using a stylesheet File object.
    """
    request = self.app.REQUEST
    addOOoTemplate = self.getPortal().manage_addProduct['ERP5OOo'].addOOoTemplate
    addOOoTemplate(id='Static_viewAsOdt', title='')
    Static_viewAsOdt = self.getPortal().Static_viewAsOdt
    # Test_getODTStyleSheet_ja is statically exist.
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_ja'))
    Static_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='Test_getODTStyleSheet_ja', script_name='')
    Static_viewAsOdt.pt_edit(self.content, content_type='application/vnd.oasis.opendocument.text')

    # 1. test a normal case
    response = self.publish('/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
    self.assertTrue(200, response.getStatus())
    self.assertEqual('application/vnd.oasis.opendocument.text',
                     response.getHeader('content-type').split(';')[0])
    self.assertEqual('attachment; filename="Static_viewAsOdt.odt"',
                     response.getHeader('content-disposition'))
    self._validate(response.getBody()) 
    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(len(styles_xml_body) > 0)
    self.assertTrue(styles_xml_body.find('Style sheet ja') > 0)

    # 2. test a normal case, change the style sheet
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_en'))
    Static_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='Test_getODTStyleSheet_en', script_name='')
    response = self.publish('/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
    self.assertTrue(200, response.getStatus())
    self._validate(response.getBody()) 
    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(len(styles_xml_body) > 0)
    self.assertTrue(styles_xml_body.find('Style sheet en') > 0)

    # 3. test a fail case
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet'))
    Static_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='NotFound_getODTStyleSheet', script_name='')
    response = self.publish('/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
    self.assertFalse(response.getBody().startswith('PK'))
    self.assertTrue(500, response.getStatus())

  def test_include_img(self):
    """
      Create an OOoTemplate from scratch, using pt_editAction to set the
      content, the content contains an include_img, when the OOo is rendered we
      have:
       - valid odf
       - an image included in the "ZIP"
       - the image properly listed in manifest
    """
    request = self.app.REQUEST
    filename = 'cmyk_sample.jpg'
    file_path = os.path.join(os.path.dirname(__file__), 'test_document',
        filename)
    upload_file = FileUpload(file_path, filename)
    document = self.portal.portal_contributions.newContent(file=upload_file)
    addOOoTemplate = self.getPortal().manage_addProduct['ERP5OOo'].addOOoTemplate
    addOOoTemplate(id='Base_viewIncludeImageAsOdt', title='')
    custom_content = self.content.replace("<office:text />",
        "<office:text><office:include_img path='%s'/></office:text>" % document.getRelativeUrl())
    Base_viewIncludeImageAsOdt = self.getPortal().Base_viewIncludeImageAsOdt
    Base_viewIncludeImageAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='Base_getODTStyleSheet',
                                script_name='')
    Base_viewIncludeImageAsOdt.pt_edit(custom_content,
        content_type='application/vnd.oasis.opendocument.text')
    self.tic()
    response = self.publish('/' + self.getPortal().Base_viewIncludeImageAsOdt.absolute_url(1))
    self.assertEqual('application/vnd.oasis.opendocument.text',
                     response.getHeader('content-type').split(';')[0])
    self.assertEqual('attachment; filename="Base_viewIncludeImageAsOdt.odt"',
                     response.getHeader('content-disposition'))
    self.assertTrue(200, response.getStatus())
    cs = StringIO()
    cs.write(response.getBody())
    zip_document = ZipFile(cs)
    picture_list = filter(lambda x: "Pictures" in x.filename,
        zip_document.infolist())
    self.assertNotEquals([], picture_list)
    manifest = zip_document.read('META-INF/manifest.xml')
    content = zip_document.read('content.xml')
    for picture in picture_list:
      self.assertTrue(picture.filename in manifest)
      self.assertTrue(picture.filename in content)
示例#13
0
class TestOOoChart(ERP5TypeTestCase, ZopeTestCase.Functional):
    """Tests OOoChart a and this render for ERP5."""
    form_id = 'TestOOochart_viewForm'
    ooo_chart_id = 'my_ooochart'
    nb_persons = 10
    content_type = 'application/vnd.oasis.opendocument.graphics'

    def getTitle(self):
      return 'Test OOoChart'

    def getBusinessTemplateList(self):
      return ('erp5_core_proxy_field_legacy',
              'erp5_base',
              'erp5_ingestion',
              'erp5_web',
              'erp5_dms',
              'erp5_ui_test',
              'erp5_odt_style',
              'erp5_ods_style')

    def afterSetUp(self):
      self.auth = 'ERP5TypeTestCase:'
      portal = self.getPortal()
      container = portal.portal_skins.custom
      if self.form_id not in container.objectIds():
        container.manage_addProduct['ERP5Form'].addERP5Form(self.form_id, 'View')
        form = getattr(container, self.form_id)

        # create some persons in person_module
        self.createPersons()
        # add a ListBox field
        form.manage_addField('listbox', 'listbox', 'ListBox')
        form.listbox.ListBox_setPropertyList(field_list_method='zCountDocumentPerOwner',
                                field_count_method='',
                                field_columns=['owner | Owner',
                                              'owner_count | Owner Count',
                                              'number_count | Reference Count'],
                                )

        # create a Field OOoChart
        form.manage_addField(self.ooo_chart_id, self.ooo_chart_id, 'OOoChart')

        # create a Field OOoChart
        form.manage_addField('your_ooochart', 'your_ooochart', 'OOoChart')



        # create a ZSQL Method
        sql = """SELECT owner, count(uid) AS owner_count,
                count(reference) AS number_count
                FROM catalog
                WHERE portal_type = 'Person'
                GROUP BY owner ORDER BY owner_count DESC"""

        template = String(source_string=sql)
        container.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod('zCountDocumentPerOwner', 'zCountDocumentPerOwner', 'erp5_sql_connection', '', template)
        # enable preference
        preference = self.getPortal().portal_preferences.default_site_preference
        preference.setPriority(1)
        if preference.getPreferenceState() == 'disabled':
          self.getWorkflowTool().doActionFor(ob=preference,
                                            action='enable_action',
                                            wf_id='preference_workflow')

      self.validator = Validator()
      self.tic()

    def createPersons(self):
      """ Create 10 persons in person_module """
      module = self.getPersonModule()
      if len(module.objectIds()) == 0:
        for i in range(self.nb_persons):
          module.newContent(portal_type='Person', id='person%s' % i)

    def _validate(self, odf_file_data):
      error_list = self.validator.validate(odf_file_data)
      if error_list:
        self.fail(''.join(error_list))

    def test_ooo_chart(self):
      portal = self.getPortal()
      # Does the form exist ?
      self.assertTrue(self.form_id in portal.portal_skins.custom.objectIds())
      getattr(aq_base(portal.portal_skins.custom), self.form_id)
      form = getattr(portal.portal_skins.custom, self.form_id)
      #listbox = form.listbox
      listbox = getattr(form, 'listbox')
      self.assertEqual(listbox.meta_type, 'ListBox')
      request = get_request()
      request['here'] = portal.portal_skins.custom
      line_list = [l for l in listbox.get_value('default',
                              render_format='list',
                              REQUEST=request) ]

      # listbox is empty?
      self.assertEqual(2, len(line_list))

      # Does the field OOoChart exist ?
      ooochart = getattr(form, self.ooo_chart_id)
      self.assertEqual(ooochart.meta_type, 'OOoChart')

      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # test render raw
      self.assertEqual(HTTP_OK, response.getStatus())
      content_type = response.getHeader('content-type')

      # test content type : application/vnd.oasis.opendocument.graphics
      self.assertTrue(content_type.startswith(self.content_type), content_type)
      content_disposition = response.getHeader('content-disposition')
      self.assertEqual('attachment', content_disposition.split(';')[0])
      # Test ODG (zip)
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      from Products.ERP5OOo.OOoUtils import OOoParser
      parser = OOoParser()
      parser.openFromString(body)
      content_xml_view = parser.oo_files['content.xml']

      doc_view = etree.fromstring(content_xml_view)
      xpath = '//@*[name() = "xlink:href"]'
      num_object = doc_view.xpath(xpath)[0][2:]

      content_xml_build = parser.oo_files['%s/content.xml' % num_object]
      doc_build = etree.fromstring(content_xml_build)
      xpath = '//@*[name() = "office:value"]'
      value_list = doc_build.xpath(xpath)
      # Test the data presence in the file XML
      self.assertNotEquals(0, len(value_list))
      # 2 values because there are - 10 document created by a owner
      #                            - 0 Reference count
      self.assertEqual(2, len(value_list))

      # Test the differents render
      # render image
      for image_format in VALID_IMAGE_FORMAT_LIST:
        response = self.publish(
                      '/%s/%s/%s?render_format=%s&display=medium'
                      % (self.portal.getId(), self.form_id, self.ooo_chart_id, image_format), self.auth )
        self.assertEqual(HTTP_OK, response.getStatus(), '%s rendering failed: %s' % (image_format, response.getStatus()))

      # render pdf
      response = self.publish(
                    '/%s/%s/%s?render_format=pdf&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      self.assertEqual(HTTP_OK, response.getStatus())


      # Change some params  and restart (circle, bar, ...)
      # chart type : circle
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:circle'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      # chart type : line
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:line'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      #chart type : scatter
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:scatter'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

    def test_proxy_ooo_chart(self):
      portal = self.getPortal()
      # Does the form exist ?
      self.assertTrue(self.form_id in portal.portal_skins.custom.objectIds())
      getattr(aq_base(portal.portal_skins.custom), self.form_id)
      form = getattr(portal.portal_skins.custom, self.form_id)

      #Proxify the Field my_ooochart
      form.proxifyField({self.ooo_chart_id:'TestOOochart_viewForm.your_ooochart'})
      # Does the field OOoChart exist ?
      ooochart = getattr(form, self.ooo_chart_id)
      self.assertEqual(ooochart.meta_type, 'ProxyField')
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # test render raw
      self.assertEqual(HTTP_OK, response.getStatus())
      content_type = response.getHeader('content-type')

      # test content type : application/vnd.oasis.opendocument.graphics
      self.assertTrue(content_type.startswith(self.content_type), content_type)
      content_disposition = response.getHeader('content-disposition')
      self.assertEqual('attachment', content_disposition.split(';')[0])
      # Test ODG (zip)
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      from Products.ERP5OOo.OOoUtils import OOoParser
      parser = OOoParser()
      parser.openFromString(body)
      content_xml_view = parser.oo_files['content.xml']

      doc_view = etree.fromstring(content_xml_view)
      xpath = '//@*[name() = "xlink:href"]'
      num_object = doc_view.xpath(xpath)[0][2:]

      content_xml_build = parser.oo_files['%s/content.xml' % num_object]
      doc_build = etree.fromstring(content_xml_build)
      xpath = '//@*[name() = "office:value"]'
      value_list = doc_build.xpath(xpath)
      # Test the data presence in the file XML
      self.assertNotEquals(0, len(value_list))
      # 2 values because there are - 10 document created by a owner
      #                            - 0 Reference count
      self.assertEqual(2, len(value_list))

      # Test the differents render
      # render image
      for image_format in VALID_IMAGE_FORMAT_LIST:
        response = self.publish(
                      '/%s/%s/%s?render_format=%s&display=medium'
                      % (self.portal.getId(), self.form_id, self.ooo_chart_id, image_format), self.auth )
        self.assertEqual(HTTP_OK, response.getStatus(), '%s rendering failed: %s' % (image_format, response.getStatus()))

      # render pdf
      response = self.publish(
                    '/%s/%s/%s?render_format=pdf&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      self.assertEqual(HTTP_OK, response.getStatus())


      # Change some params  and restart (circle, bar, ...)
      # chart type : circle
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:circle'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      # chart type : line
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:line'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      #chart type : scatter
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:scatter'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

    def test_ods_style(self):
      # simple rendering of a chart in ods style
      self.portal.changeSkin('ODS')
      response = self.publish(
          '/%s/%s' % (self.portal.getId(), self.form_id),
          self.auth,
          handle_errors=False )
      self.assertEqual(HTTP_OK, response.getStatus())
      body = response.getBody()
      self._validate(body)

    def test_odt_style(self):
      # simple rendering of a chart in odt style
      self.portal.changeSkin('ODT')
      response = self.publish(
          '/%s/%s' % (self.portal.getId(), self.form_id),
          self.auth,
          handle_errors=False )
      self.assertEqual(HTTP_OK, response.getStatus())
      body = response.getBody()
      self._validate(body)
示例#14
0
    def pt_render(self, source=0, extra_context={}):
        # Get request
        request = extra_context.get('REQUEST', self.REQUEST)
        # Get parent object (the one to render this template on)
        here = getattr(self, 'aq_parent', None)
        if here is None:
            # This is a system error
            raise ValueError, 'Can not render a template without a parent acquisition context'
        # Retrieve master document
        ooo_document = None
        # If script is setting, call it
        if self.ooo_script_name:
            ooo_script = getattr(here, self.ooo_script_name)
            ooo_document = ooo_script(self.ooo_stylesheet)
        else:
            ooo_document = getattr(here, self.ooo_stylesheet)
        format = request.get('format')
        try:
            # If style is dynamic, call it
            if getattr(aq_base(ooo_document), '__call__', None) is not None:
                request.set('format', None)
                ooo_document = ooo_document()
        finally:
            request.set('format', format)
        # Create a new builder instance
        ooo_builder = OOoBuilder(ooo_document)
        # Pass builder instance as extra_context
        extra_context['ooo_builder'] = ooo_builder

        # And render page template
        doc_xml = ZopePageTemplate.pt_render(self,
                                             source=source,
                                             extra_context=extra_context)
        if isinstance(doc_xml, unicode):
            doc_xml = doc_xml.encode('utf-8')

        # Replace the includes
        (doc_xml,
         attachments_dict) = self.renderIncludes(here, doc_xml, extra_context,
                                                 request)

        try:
            default_styles_text = ooo_builder.extract('styles.xml')
        except AttributeError:
            default_styles_text = None

        # Add the associated files
        for dir_name, document_dict in attachments_dict.iteritems():
            # Special case : the document is an OOo one
            if document_dict['doc_type'].startswith(self._OOo_content_type_root) or \
               document_dict['doc_type'].startswith(self._ODF_content_type_root):
                ooo_builder.addFileEntry(full_path=dir_name,
                                         media_type=document_dict['doc_type'])
                ooo_builder.addFileEntry(full_path=dir_name + '/content.xml',
                                         media_type='text/xml',
                                         content=document_dict['document'])
                styles_text = default_styles_text
                if document_dict.has_key(
                        'stylesheet') and document_dict['stylesheet']:
                    styles_text = document_dict['stylesheet']
                if styles_text:
                    ooo_builder.addFileEntry(full_path=dir_name +
                                             '/styles.xml',
                                             media_type='text/xml',
                                             content=styles_text)
            else:  # Generic case
                ooo_builder.addFileEntry(full_path=dir_name,
                                         media_type=document_dict['doc_type'],
                                         content=document_dict['document'])

        # Replace content.xml in master openoffice template
        ooo_builder.replace(self.ooo_xml_file_id, doc_xml)

        # Old templates correction
        try:
            self.OLE_documents_zipstring
        except AttributeError:
            self.OLE_documents_zipstring = None

        # Convert if necessary
        opts = extra_context.get("options", dict())

        # Get batch_mode
        batch_mode = opts.get('batch_mode', None)

        # If the file has embedded OLE documents, restore them
        if self.OLE_documents_zipstring:
            additional_builder = OOoBuilder(self.OLE_documents_zipstring)
            for name in additional_builder.getNameList():
                if name not in ('META-INF/manifest.xml', ):
                    # We don't replace manifest
                    ooo_builder.replace(name, additional_builder.extract(name))

        # Update the META information
        ooo_builder.updateManifest()

        # Produce final result
        if batch_mode:
            ooo = ooo_builder.render()
        else:
            ooo = ooo_builder.render(name=self.title or self.id, source=source)

        if DevelopmentMode:
            # Validate XML in development mode
            from Products.ERP5OOo.tests.utils import Validator
            err_list = Validator().validate(ooo)
            if err_list:
                LOG(
                    'ERP5OOo', PROBLEM, 'Validation of %s failed:\n%s' %
                    (self.getId(), ''.join(err_list)))

        extension = None
        mimetype = ooo_builder.getMimeType()
        mimetypes_registry = self.getPortalObject().mimetypes_registry
        mimetype_object_list = mimetypes_registry.lookup(mimetype)
        for mimetype_object in mimetype_object_list:
            if mimetype_object.extensions:
                extension = mimetype_object.extensions[0]
                break
            elif mimetype_object.globs:
                extension = mimetype_object.globs.strip('*.')
                break
        if extension:
            filename = '%s.%s' % (self._getFileName(), extension)
        else:
            filename = self._getFileName()

        from Products.ERP5Type.Document import newTempOOoDocument
        tmp_ooo = newTempOOoDocument(self, self.title_or_id())
        tmp_ooo.edit(
            data=ooo,
            filename=filename,
            content_type=mimetype,
        )

        format = opts.get('format', request.get('format', None))
        if format:
            # Performance improvement:
            # We already have OOo format data, so we do not need to call
            # convertToBaseFormat(), but just copy it into base_data property.
            tmp_ooo.setBaseData(ooo)
            tmp_ooo.setBaseContentType(mimetype)

        if request is not None and not batch_mode and not source:
            return tmp_ooo.index_html(REQUEST=request,
                                      RESPONSE=request.RESPONSE,
                                      format=format)
        return tmp_ooo.convert(format)[1]
示例#15
0
class TestOOoChart(ERP5TypeTestCase, ZopeTestCase.Functional):
    """Tests OOoChart a and this render for ERP5."""
    form_id = 'TestOOochart_viewForm'
    ooo_chart_id = 'my_ooochart'
    nb_persons = 10
    content_type = 'application/vnd.oasis.opendocument.graphics'

    def getTitle(self):
      return 'Test OOoChart'

    def getBusinessTemplateList(self):
      return ('erp5_core_proxy_field_legacy',
              'erp5_base',
              'erp5_ingestion',
              'erp5_web',
              'erp5_dms',
              'erp5_ui_test',
              'erp5_odt_style',
              'erp5_ods_style')

    def afterSetUp(self):
      self.auth = 'ERP5TypeTestCase:'
      portal = self.getPortal()
      container = portal.portal_skins.custom
      if self.form_id not in container.objectIds():
        container._setObject(self.form_id, ERP5Form(self.form_id, 'View'))
        form = getattr(container, self.form_id)

        # create some persons in person_module
        self.createPersons()
        # add a ListBox field
        form.manage_addField('listbox', 'listbox', 'ListBox')
        form.listbox.ListBox_setPropertyList(field_list_method='zCountDocumentPerOwner',
                                field_count_method='',
                                field_columns=['owner | Owner',
                                              'owner_count | Owner Count',
                                              'number_count | Reference Count'],
                                )

        # create a Field OOoChart
        form.manage_addField(self.ooo_chart_id, self.ooo_chart_id, 'OOoChart')

        # create a Field OOoChart
        form.manage_addField('your_ooochart', 'your_ooochart', 'OOoChart')



        # create a ZSQL Method
        sql = """SELECT owner, count(uid) AS owner_count,
                count(reference) AS number_count
                FROM catalog
                WHERE portal_type = 'Person'
                GROUP BY owner ORDER BY owner_count DESC"""

        template = String(source_string=sql)
        container.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod('zCountDocumentPerOwner', 'zCountDocumentPerOwner', 'erp5_sql_connection', '', template)
        # enable preference
        preference = self.getPortal().portal_preferences.default_site_preference
        preference.setPriority(1)
        if preference.getPreferenceState() == 'disabled':
          self.getWorkflowTool().doActionFor(ob=preference,
                                            action='enable_action',
                                            wf_id='preference_workflow')

      self.validator = Validator()
      self.tic()

    def createPersons(self):
      """ Create 10 persons in person_module """
      module = self.getPersonModule()
      if len(module.objectIds()) == 0:
        for i in range(self.nb_persons):
          module.newContent(portal_type='Person', id='person%s' % i)

    def _validate(self, odf_file_data):
      error_list = self.validator.validate(odf_file_data)
      if error_list:
        self.fail(''.join(error_list))

    def test_ooo_chart(self):
      portal = self.getPortal()
      # Does the form exist ?
      self.assertTrue(self.form_id in portal.portal_skins.custom.objectIds())
      getattr(aq_base(portal.portal_skins.custom), self.form_id)
      form = getattr(portal.portal_skins.custom, self.form_id)
      #listbox = form.listbox
      listbox = getattr(form, 'listbox')
      self.assertEqual(listbox.meta_type, 'ListBox')
      request = get_request()
      request['here'] = portal.portal_skins.custom
      line_list = [l for l in listbox.get_value('default',
                              render_format='list',
                              REQUEST=request) ]

      # listbox is empty?
      self.assertEqual(2, len(line_list))

      # Does the field OOoChart exist ?
      ooochart = getattr(form, self.ooo_chart_id)
      self.assertEqual(ooochart.meta_type, 'OOoChart')

      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # test render raw
      self.assertEqual(HTTP_OK, response.getStatus())
      content_type = response.getHeader('content-type')

      # test content type : application/vnd.oasis.opendocument.graphics
      self.assertTrue(content_type.startswith(self.content_type), content_type)
      content_disposition = response.getHeader('content-disposition')
      self.assertEqual('attachment', content_disposition.split(';')[0])
      # Test ODG (zip)
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      from Products.ERP5OOo.OOoUtils import OOoParser
      parser = OOoParser()
      parser.openFromString(body)
      content_xml_view = parser.oo_files['content.xml']

      doc_view = etree.fromstring(content_xml_view)
      xpath = '//@*[name() = "xlink:href"]'
      num_object = doc_view.xpath(xpath)[0][2:]

      content_xml_build = parser.oo_files['%s/content.xml' % num_object]
      doc_build = etree.fromstring(content_xml_build)
      xpath = '//@*[name() = "office:value"]'
      value_list = doc_build.xpath(xpath)
      # Test the data presence in the file XML
      self.assertNotEquals(0, len(value_list))
      # 2 values because there are - 10 document created by a owner
      #                            - 0 Reference count
      self.assertEqual(2, len(value_list))

      # Test the differents render
      # render image
      for image_format in VALID_IMAGE_FORMAT_LIST:
        response = self.publish(
                      '/%s/%s/%s?render_format=%s&display=medium'
                      % (self.portal.getId(), self.form_id, self.ooo_chart_id, image_format), self.auth )
        self.assertEqual(HTTP_OK, response.getStatus(), '%s rendering failed: %s' % (image_format, response.getStatus()))

      # render pdf
      response = self.publish(
                    '/%s/%s/%s?render_format=pdf&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      self.assertEqual(HTTP_OK, response.getStatus())


      # Change some params  and restart (circle, bar, ...)
      # chart type : circle
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:circle'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      # chart type : line
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:line'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      #chart type : scatter
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:scatter'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

    def test_proxy_ooo_chart(self):
      portal = self.getPortal()
      # Does the form exist ?
      self.assertTrue(self.form_id in portal.portal_skins.custom.objectIds())
      getattr(aq_base(portal.portal_skins.custom), self.form_id)
      form = getattr(portal.portal_skins.custom, self.form_id)

      #Proxify the Field my_ooochart
      form.proxifyField({self.ooo_chart_id:'TestOOochart_viewForm.your_ooochart'})
      # Does the field OOoChart exist ?
      ooochart = getattr(form, self.ooo_chart_id)
      self.assertEqual(ooochart.meta_type, 'ProxyField')
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # test render raw
      self.assertEqual(HTTP_OK, response.getStatus())
      content_type = response.getHeader('content-type')

      # test content type : application/vnd.oasis.opendocument.graphics
      self.assertTrue(content_type.startswith(self.content_type), content_type)
      content_disposition = response.getHeader('content-disposition')
      self.assertEqual('attachment', content_disposition.split(';')[0])
      # Test ODG (zip)
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      from Products.ERP5OOo.OOoUtils import OOoParser
      parser = OOoParser()
      parser.openFromString(body)
      content_xml_view = parser.oo_files['content.xml']

      doc_view = etree.fromstring(content_xml_view)
      xpath = '//@*[name() = "xlink:href"]'
      num_object = doc_view.xpath(xpath)[0][2:]

      content_xml_build = parser.oo_files['%s/content.xml' % num_object]
      doc_build = etree.fromstring(content_xml_build)
      xpath = '//@*[name() = "office:value"]'
      value_list = doc_build.xpath(xpath)
      # Test the data presence in the file XML
      self.assertNotEquals(0, len(value_list))
      # 2 values because there are - 10 document created by a owner
      #                            - 0 Reference count
      self.assertEqual(2, len(value_list))

      # Test the differents render
      # render image
      for image_format in VALID_IMAGE_FORMAT_LIST:
        response = self.publish(
                      '/%s/%s/%s?render_format=%s&display=medium'
                      % (self.portal.getId(), self.form_id, self.ooo_chart_id, image_format), self.auth )
        self.assertEqual(HTTP_OK, response.getStatus(), '%s rendering failed: %s' % (image_format, response.getStatus()))

      # render pdf
      response = self.publish(
                    '/%s/%s/%s?render_format=pdf&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      self.assertEqual(HTTP_OK, response.getStatus())


      # Change some params  and restart (circle, bar, ...)
      # chart type : circle
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:circle'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      # chart type : line
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:line'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

      #chart type : scatter
      form.my_ooochart.manage_edit_xmlrpc(dict(chart_type='chart:scatter'))
      response = self.publish(
                    '/%s/%s/%s?render_format=&display=medium'
                    % (self.portal.getId(), self.form_id, self.ooo_chart_id), self.auth )
      # Test ODG (zip) with other params
      body = response.getBody()
      # Test Validation Relax NG
      self._validate(body)

    def test_ods_style(self):
      # simple rendering of a chart in ods style
      self.portal.changeSkin('ODS')
      response = self.publish(
          '/%s/%s' % (self.portal.getId(), self.form_id),
          self.auth,
          handle_errors=False )
      self.assertEqual(HTTP_OK, response.getStatus())
      body = response.getBody()
      self._validate(body)

    def test_odt_style(self):
      # simple rendering of a chart in odt style
      self.portal.changeSkin('ODT')
      response = self.publish(
          '/%s/%s' % (self.portal.getId(), self.form_id),
          self.auth,
          handle_errors=False )
      self.assertEqual(HTTP_OK, response.getStatus())
      body = response.getBody()
      self._validate(body)
示例#16
0
class TestOOoStyle(ERP5TypeTestCase, ZopeTestCase.Functional):
  """Tests ODF styles for ERP5."""
  skin = None
  content_type = None

  def getBusinessTemplateList(self):
    return ('erp5_core_proxy_field_legacy',
            'erp5_base', 'erp5_ods_style', 'erp5_odt_style',)

  def afterSetUp(self):
    if not self.skin:
      raise NotImplementedError('Subclasses must define skin')

    self.setDefaultSitePreference()

    gender = self.portal.portal_categories.gender
    if 'male' not in gender.objectIds():
      gender.newContent(id='male')
      self.portal.portal_caches.clearAllCache()

    self.auth = 'ERP5TypeTestCase:'
    person_module = self.portal.person_module
    if person_module._getOb('pers', None) is None:
      person_module.newContent(id='pers', portal_type='Person')
      self.tic()
    person_module.pers.setFirstName('Bob')
    person_module.pers.setGender(None)
    person_module.pers.setCareerRole(None)

    if person_module.pers._getOb('img', None) is None:
      person_module.pers.newContent(portal_type='Embedded File', id='img')

    if person_module._getOb('pers_without_image', None) is None:
      person = person_module.newContent(
                              portal_type='Person',
                              id = 'pers_without_image',
                              first_name = 'Test')
      self.tic()

    self.portal.changeSkin(self.skin)
    self.validator = Validator()
    # make sure selections are empty
    name = 'person_module_selection'
    self.portal.portal_selections.setSelectionFor(name, Selection(name))

  def setDefaultSitePreference(self):
    default_pref = self.portal.portal_preferences.default_site_preference
    conversion_dict = _getConversionServerDict()
    default_pref.setPreferredOoodocServerAddress(conversion_dict['hostname'])
    default_pref.setPreferredOoodocServerPortNumber(conversion_dict['port'])
    if self.portal.portal_workflow.isTransitionPossible(default_pref, 'enable'):
      default_pref.enable()
    return default_pref

  def publish(self, *args, **kw):
    kw['handle_errors'] = not debug
    return super(TestOOoStyle, self).publish(*args, **kw)

  def _validate(self, odf_file_data):
    error_list = self.validator.validate(odf_file_data)
    if error_list:
      self.fail(''.join(error_list))
  
  def _assertFieldInGroup(self, field_type, form_id, group):
    for f in getattr(self.portal, form_id).get_fields_in_group(group):
      if f.meta_type == 'ProxyField':
        if f.getRecursiveTemplateField().meta_type == field_type:
          break
      if f.meta_type == field_type:
        break
    else:
      self.fail('No %s found in %s (%s group)' % (field_type, form_id, group))

  def test_skin_selection(self):
    self.assertTrue(self.skin in
              self.portal.portal_skins.getSkinSelections())

  def test_form_list(self):
    response = self.publish(
                   '/%s/person_module/PersonModule_viewPersonList'
                    % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_list_domain_tree(self):
    self.portal.portal_selections.setListboxDisplayMode(
                  self.portal.REQUEST, 'DomainTreeMode',
                  'person_module_selection')
    # XXX no proper API on selection / selection tool for this ?
    self.portal.portal_selections.setSelectionParamsFor(
                  selection_name='person_module_selection',
                  params=dict(domain_path='portal_categories',
                              domain_url='group',
                              domain_list=()))
    response = self.publish(
                   '/%s/person_module/PersonModule_viewPersonList'
                    % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view(self):
    # form_view on a form without listbox
    self.portal.person_module.pers.setDefaultAddressZipCode(59000)
    response = self.publish(
        '/%s/person_module/pers/default_address/GeographicAddress_view'
        % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_empty_listbox(self):
    # form_view on a form with an empty listbox
    if hasattr(self.portal.person_module.pers, 'default_address'):
      self.portal.person_module.pers._delObject('default_address')
    response = self.publish(
                   '/%s/person_module/pers/Person_view'
                   % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_non_empty_listbox(self):
    self.portal.person_module.pers.setDefaultAddressZipCode(59000)
    response = self.publish(
                   '/%s/person_module/pers/Person_view'
                   % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_format(self):
    # empty format= does not use oood for conversion
    response = self.publish(
                   '/%s/person_module/pers/Person_view?format='
                   % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())
    # format=pdf uses oood for conversion
    response = self.publish(
                   '/%s/person_module/pers/Person_view?format=pdf'
                   % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertEquals(content_type, 'application/pdf')
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])

  def test_report_view_form_view(self):
    # Test report view rendering forms using form_view
    self.assertEquals('form_view', self.portal.Base_viewWorkflowHistory.pt)
    response = self.publish(
                   '/%s/person_module/pers/Base_viewHistory'
                    % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_report_view_form_list(self):
    # Test report view rendering forms using form_list
    self.portal.Base_viewWorkflowHistory.pt = 'form_list'
    try:
      # publish commits a transaction, so we have to restore the original page
      # template on the form
      response = self.publish(
                   '/%s/person_module/pers/Base_viewHistory'
                    % self.portal.getId(), self.auth)
    finally:
      self.portal.Base_viewWorkflowHistory.pt = 'form_view'
      self.commit()
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())


  def test_report_view_landscape(self):
    response = self.publish(
       '/%s/person_module/pers/Base_viewHistory?landscape=1'
        % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_report_view_sheet_per_report_section(self):
    response = self.publish(
       '/%s/person_module/pers/Base_viewHistory?sheet_per_report_section=1'
        % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_encoding(self):
    self.portal.person_module.pers.setFirstName('Jérome')
    response = self.publish('/%s/person_module/pers/Person_view'
                          % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_category(self):
    self.portal.person_module.pers.setGender('male')
    response = self.publish('/%s/person_module/pers/Person_view'
                          % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_broken_category(self):
    self.portal.person_module.pers.setGender('not exist')
    self.portal.person_module.pers.setCareerRole('not exist')
    response = self.publish('/%s/person_module/pers/Person_view'
                          % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_embedded_image(self):
    # with image
    response = self.publish('/%s/person_module/pers/Person_viewDetails'
                          % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())
    # without image
    response = self.publish('/%s/person_module/pers_without_image/Person_viewDetails'
                          % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_report_view_encoding(self):
    self.portal.person_module.pers.setFirstName('Jérome')
    response = self.publish('/%s/person_module/pers/Base_viewHistory'
                          % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_list_encoding(self):
    self.portal.person_module.pers.setFirstName('Jérome')
    response = self.publish(
       '/%s/person_module/PersonModule_viewPersonList'
        % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_image_field_form_view(self):
    self._assertFieldInGroup('ImageField', 'Image_view', 'right')
    response = self.publish(
       '/%s/person_module/pers/img/Image_view'
        % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_image_field_form_view_bottom_group(self):
    self._assertFieldInGroup(
        'ImageField', 'Image_viewFullSizedImage', 'bottom')
    response = self.publish(
       '/%s/person_module/pers/img/Image_viewFullSizedImage'
        % self.portal.getId(), basic=self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_textarea_center_group(self):
    self._assertFieldInGroup('TextAreaField', 'Person_view', 'center')
    self.assert_('my_description' in [f.getId() for f in
        self.portal.Person_view.get_fields_in_group('center')])
    self.portal.person_module.pers.setDescription('<Escape>&\nnewline')
    response = self.publish(
                   '/%s/person_module/pers/Person_view'
                   % self.portal.getId(), self.auth)
    self.assertEquals(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEquals('attachment', content_disposition.split(';')[0])
    body = response.getBody()
    self._validate(body)

    if self.skin == 'ODT':
      # Is it good to do this only for ODT ?
      from Products.ERP5OOo.OOoUtils import OOoParser
      parser = OOoParser()
      parser.openFromString(body)
      content_xml = parser.oo_files['content.xml']
      self.assert_('&lt;Escape&gt;&amp;<text:line-break/>newline' in content_xml)
示例#17
0
class TestOooDynamicStyle(ERP5TypeTestCase):
    manager_username = '******'
    manager_password = '******'
    content_type_writer = 'application/vnd.oasis.opendocument.text'
    content = "<office:document-content xmlns:draw='urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0' xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0' xmlns:ooo='http://openoffice.org/2004/office' xmlns:number='urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0' xmlns:table='urn:oasis:names:tc:opendocument:xmlns:table:1.0' xmlns:dr3d='urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0' xmlns:fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0' xmlns:style='urn:oasis:names:tc:opendocument:xmlns:style:1.0' xmlns:xforms='http://www.w3.org/2002/xforms' xmlns:form='urn:oasis:names:tc:opendocument:xmlns:form:1.0' xmlns:script='urn:oasis:names:tc:opendocument:xmlns:script:1.0' xmlns:ooow='http://openoffice.org/2004/writer' xmlns:svg='urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0' xmlns:chart='urn:oasis:names:tc:opendocument:xmlns:chart:1.0' xmlns:dom='http://www.w3.org/2001/xml-events' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:oooc='http://openoffice.org/2004/calc' xmlns:math='http://www.w3.org/1998/Math/MathML' xmlns:tal='http://xml.zope.org/namespaces/tal' office:version='1.2'><office:scripts /><office:font-face-decls /><office:automatic-styles /><office:body><office:text /></office:body></office:document-content>"

    def getTitle(self):
        return "TestOOoDynamicStyle"

    def getBusinessTemplateList(self):
        return ('erp5_core_proxy_field_legacy',
                'erp5_full_text_mroonga_catalog', 'erp5_base',
                'erp5_ingestion_mysql_innodb_catalog', 'erp5_ingestion',
                'erp5_web', 'erp5_dms', 'erp5_odt_style')

    def afterSetUp(self):
        self.login()
        self.getPortal().Localizer = DummyLocalizer()
        v12schema_url = os.path.join(os.path.dirname(__file__),
                                     'OpenDocument-v1.2-os-schema.rng')
        self.validator = Validator(schema_url=v12schema_url)
        en_file_path = os.path.join(os.path.dirname(__file__), 'test_document',
                                    'DYNAMIC_STYLE_en.odt')
        en_file = open(en_file_path, 'rb')
        ja_file_path = os.path.join(os.path.dirname(__file__), 'test_document',
                                    'DYNAMIC_STYLE_ja.odt')
        ja_file = open(ja_file_path, 'rb')

        addStyleSheet = self.getPortal(
        ).manage_addProduct['OFSP'].manage_addFile
        if getattr(self.getPortal(), 'Test_getODTStyleSheet_en', None) is None:
            addStyleSheet(id='Test_getODTStyleSheet_en',
                          file=en_file,
                          title='',
                          precondition='',
                          content_type=self.content_type_writer)
        if getattr(self.getPortal(), 'Test_getODTStyleSheet_ja', None) is None:
            addStyleSheet(id='Test_getODTStyleSheet_ja',
                          file=ja_file,
                          title='',
                          precondition='',
                          content_type=self.content_type_writer)
        if getattr(self.getPortal(), 'Base_getODTStyleSheetByLanguage',
                   None) is None:
            script_body = """
current_language = context.Localizer.get_selected_language()
return getattr(context, "%s_%s" % (parameter, current_language))
"""
            dispatcher = self.getPortal().manage_addProduct['PythonScripts']
            dispatcher.manage_addPythonScript(
                'Base_getODTStyleSheetByLanguage')
            script = self.getPortal().Base_getODTStyleSheetByLanguage
            script.ZPythonScript_edit('parameter', script_body)

    def _validate(self, odf_file_data):
        error_list = self.validator.validate(odf_file_data)
        if error_list:
            self.fail(''.join(error_list))

    def test_01_dynamic(self):
        """
    Test applying stylesheet dynamically, using a Python Script with
    a stylesheet file name parameter.
    """
        request = self.app.REQUEST
        addOOoTemplate = self.getPortal(
        ).manage_addProduct['ERP5OOo'].addOOoTemplate
        addOOoTemplate(id='Dynamic_viewAsOdt', title='')
        Dynamic_viewAsOdt = self.getPortal().Dynamic_viewAsOdt
        # The stylesheet file 'Test_getODTStyleSheet' is not exist in this site.
        # So, the 'Base_getODTStyleSheet', a python script creates dynamically
        # exsited stylesheet file name.
        self.assertFalse(self.getPortal().hasObject('Test_getODTStyleSheet'))
        self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_ja'))
        self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_en'))
        Dynamic_viewAsOdt.doSettings(
            request,
            title='',
            xml_file_id='content.xml',
            ooo_stylesheet='Test_getODTStyleSheet',
            script_name='Base_getODTStyleSheetByLanguage')
        Dynamic_viewAsOdt.pt_edit(
            self.content,
            content_type='application/vnd.oasis.opendocument.text')

        # 1. test a normal case, language: ja
        self.getPortal().Localizer.changeLanguage('ja')
        response = self.publish(
            '/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
        self.assertEqual('application/vnd.oasis.opendocument.text',
                         response.getHeader('content-type').split(';')[0])
        self.assertEqual('attachment; filename="Dynamic_viewAsOdt.odt"',
                         response.getHeader('content-disposition'))
        self._validate(response.getBody())
        self.assertEqual(200, response.getStatus())

        ooo_builder = OOoBuilder(response.getBody())
        styles_xml_body = ooo_builder.extract('styles.xml')
        self.assertTrue(len(styles_xml_body) > 0)
        # 'Style sheet ja' text is in the odt document header,
        # and the header is in the 'styles.xml'.
        self.assertTrue(styles_xml_body.find('Style sheet ja') > 0)

        # 2. test a normal case, change the language to 'en',
        #    so that the stylesheet changes dynamically.
        self.getPortal().Localizer = DummyLocalizer()
        self.getPortal().Localizer.changeLanguage('en')
        response = self.publish(
            '/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
        self._validate(response.getBody())
        ooo_builder = OOoBuilder(response.getBody())
        styles_xml_body = ooo_builder.extract('styles.xml')
        self.assertTrue(styles_xml_body.find('Style sheet en') > 0)

        # 3. test a fail case, reset a not existed stylesheet
        Dynamic_viewAsOdt.doSettings(
            request,
            title='',
            xml_file_id='content.xml',
            ooo_stylesheet='NotFound_getODTStyleSheet',
            script_name='Base_getODTStyleSheet')
        self.assertFalse(
            self.getPortal().hasObject('NotFound_getODTStyleSheet'))
        self.assertFalse(
            self.getPortal().hasObject('NotFound_getODTStyleSheet_ja'))
        self.assertFalse(
            self.getPortal().hasObject('NotFound_getODTStyleSheet_en'))
        self.getPortal().Localizer.changeLanguage('en')
        response = self.publish(
            '/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
        # then, it is not a zip stream
        self.assertFalse(response.getBody().startswith('PK'))
        self.assertEqual(500, response.getStatus())

    def test_02_static(self):
        """
    Test applying stylesheet statically, using a stylesheet File object.
    """
        request = self.app.REQUEST
        addOOoTemplate = self.getPortal(
        ).manage_addProduct['ERP5OOo'].addOOoTemplate
        addOOoTemplate(id='Static_viewAsOdt', title='')
        Static_viewAsOdt = self.getPortal().Static_viewAsOdt
        # Test_getODTStyleSheet_ja is statically exist.
        self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_ja'))
        Static_viewAsOdt.doSettings(request,
                                    title='',
                                    xml_file_id='content.xml',
                                    ooo_stylesheet='Test_getODTStyleSheet_ja',
                                    script_name='')
        Static_viewAsOdt.pt_edit(
            self.content,
            content_type='application/vnd.oasis.opendocument.text')

        # 1. test a normal case
        response = self.publish(
            '/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
        self.assertEqual(200, response.getStatus())
        self.assertEqual('application/vnd.oasis.opendocument.text',
                         response.getHeader('content-type').split(';')[0])
        self.assertEqual('attachment; filename="Static_viewAsOdt.odt"',
                         response.getHeader('content-disposition'))
        self._validate(response.getBody())
        ooo_builder = OOoBuilder(response.getBody())
        styles_xml_body = ooo_builder.extract('styles.xml')
        self.assertTrue(len(styles_xml_body) > 0)
        self.assertTrue(styles_xml_body.find('Style sheet ja') > 0)

        # 2. test a normal case, change the style sheet
        self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_en'))
        Static_viewAsOdt.doSettings(request,
                                    title='',
                                    xml_file_id='content.xml',
                                    ooo_stylesheet='Test_getODTStyleSheet_en',
                                    script_name='')
        response = self.publish(
            '/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
        self.assertEqual(200, response.getStatus())
        self._validate(response.getBody())
        ooo_builder = OOoBuilder(response.getBody())
        styles_xml_body = ooo_builder.extract('styles.xml')
        self.assertTrue(len(styles_xml_body) > 0)
        self.assertTrue(styles_xml_body.find('Style sheet en') > 0)

        # 3. test a fail case
        self.assertFalse(
            self.getPortal().hasObject('NotFound_getODTStyleSheet'))
        Static_viewAsOdt.doSettings(request,
                                    title='',
                                    xml_file_id='content.xml',
                                    ooo_stylesheet='NotFound_getODTStyleSheet',
                                    script_name='')
        response = self.publish(
            '/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
        self.assertFalse(response.getBody().startswith('PK'))
        self.assertEqual(500, response.getStatus())

    def test_include_img(self):
        """
      Create an OOoTemplate from scratch, using pt_editAction to set the
      content, the content contains an include_img, when the OOo is rendered we
      have:
       - valid odf
       - an image included in the "ZIP"
       - the image properly listed in manifest
    """
        request = self.app.REQUEST
        filename = 'cmyk_sample.jpg'
        file_path = os.path.join(os.path.dirname(__file__), 'test_document',
                                 filename)
        upload_file = FileUpload(file_path)
        document = self.portal.portal_contributions.newContent(
            file=upload_file)
        addOOoTemplate = self.getPortal(
        ).manage_addProduct['ERP5OOo'].addOOoTemplate
        addOOoTemplate(id='Base_viewIncludeImageAsOdt', title='')
        custom_content = self.content.replace(
            "<office:text />",
            "<office:text><office:include_img path='%s'/></office:text>" %
            document.getRelativeUrl())
        Base_viewIncludeImageAsOdt = self.getPortal(
        ).Base_viewIncludeImageAsOdt
        Base_viewIncludeImageAsOdt.doSettings(
            request,
            title='',
            xml_file_id='content.xml',
            ooo_stylesheet='Base_getODTStyleSheet',
            script_name='')
        Base_viewIncludeImageAsOdt.pt_edit(
            custom_content,
            content_type='application/vnd.oasis.opendocument.text')
        self.tic()

        response = self.publish(
            '/' + self.getPortal().Base_viewIncludeImageAsOdt.absolute_url(1))
        body = response.getBody()
        self.assertEqual(200, response.getStatus(), body)
        self.assertEqual('application/vnd.oasis.opendocument.text',
                         response.getHeader('content-type').split(';')[0])
        self.assertEqual(
            'attachment; filename="Base_viewIncludeImageAsOdt.odt"',
            response.getHeader('content-disposition'))
        cs = StringIO()
        cs.write(body)
        zip_document = ZipFile(cs)
        picture_list = filter(lambda x: "Pictures" in x.filename,
                              zip_document.infolist())
        self.assertNotEquals([], picture_list)
        manifest = zip_document.read('META-INF/manifest.xml')
        content = zip_document.read('content.xml')
        for picture in picture_list:
            self.assertTrue(picture.filename in manifest)
            self.assertTrue(picture.filename in content)
示例#18
0
class TestOOoChartMixin(ERP5TypeTestCase, ZopeTestCase.Functional):
    """Tests OOoChart a and this render for ERP5."""
    form_id = 'TestOOochart_viewForm'
    ooo_chart_id = 'my_ooochart'
    nb_persons = 10
    content_type = 'application/vnd.oasis.opendocument.graphics'

    def afterSetUp(self):
        self.auth = 'ERP5TypeTestCase:'
        portal = self.getPortal()
        container = portal.portal_skins.custom
        if self.form_id not in container.objectIds():
            container.manage_addProduct['ERP5Form'].addERP5Form(
                self.form_id, 'View')
            form = getattr(container, self.form_id)

            # create some persons in person_module
            self.createPersons()
            # add a ListBox field
            form.manage_addField('listbox', 'listbox', 'ListBox')
            form.listbox.ListBox_setPropertyList(
                field_list_method='zCountDocumentPerOwner',
                field_count_method='',
                field_columns=[
                    'owner | Owner', 'owner_count | Owner Count',
                    'number_count | Reference Count'
                ],
            )

            # create a Field OOoChart
            form.manage_addField(self.ooo_chart_id, self.ooo_chart_id,
                                 'OOoChart')

            # create a Field OOoChart
            form.manage_addField('your_ooochart', 'your_ooochart', 'OOoChart')

            # create a ZSQL Method
            sql = """SELECT owner, count(uid) AS owner_count,
              count(reference) AS number_count
              FROM catalog
              WHERE portal_type = 'Person'
              GROUP BY owner ORDER BY owner_count DESC"""

            template = String(source_string=sql)
            container.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod(
                'zCountDocumentPerOwner', 'zCountDocumentPerOwner',
                'erp5_sql_connection', '', template)
            # enable preference
            preference = self.getPortal(
            ).portal_preferences.default_site_preference
            preference.setPriority(1)
            if preference.getPreferenceState() == 'disabled':
                self.getWorkflowTool().doActionFor(ob=preference,
                                                   action='enable_action',
                                                   wf_id='preference_workflow')

        self.validator = Validator()
        self.tic()

    def createPersons(self):
        """ Create 10 persons in person_module """
        module = self.getPersonModule()
        if len(module.objectIds()) == 0:
            for i in range(self.nb_persons):
                module.newContent(portal_type='Person', id='person%s' % i)

    def _validate(self, odf_file_data):
        error_list = self.validator.validate(odf_file_data)
        if error_list:
            self.fail(''.join(error_list))
示例#19
0
class TestOOoStyle(ERP5TypeTestCase, ZopeTestCase.Functional):
  """Tests ODF styles for ERP5."""
  skin = None
  content_type = None

  def getBusinessTemplateList(self):
    return ('erp5_core_proxy_field_legacy', 'erp5_ui_test', 'erp5_base',
            'erp5_ods_style', 'erp5_odt_style',)

  def afterSetUp(self):
    if not self.skin:
      raise NotImplementedError('Subclasses must define skin')

    gender = self.portal.portal_categories.gender
    if 'male' not in gender.objectIds():
      gender.newContent(id='male')
      self.portal.portal_caches.clearAllCache()

    self.auth = 'ERP5TypeTestCase:'
    person_module = self.portal.person_module
    if person_module._getOb('pers', None) is None:
      person_module.newContent(id='pers', portal_type='Person')
      self.tic()
    person_module.pers.setFirstName('Bob')
    person_module.pers.setGender(None)
    person_module.pers.setCareerRole(None)

    if person_module.pers._getOb('img', None) is None:
      person_module.pers.newContent(portal_type='Embedded File', id='img')

    if person_module._getOb('pers_without_image', None) is None:
      person = person_module.newContent(
                              portal_type='Person',
                              id = 'pers_without_image',
                              first_name = 'Test')
      self.tic()

    self.portal.changeSkin(self.skin)
    self.validator = Validator()
    # make sure selections are empty
    name = 'person_module_selection'
    self.portal.portal_selections.setSelectionFor(name, Selection(name))

  def publish(self, *args, **kw):
    kw['handle_errors'] = not debug
    return super(TestOOoStyle, self).publish(*args, **kw)

  def _validate(self, odf_file_data):
    error_list = self.validator.validate(odf_file_data)
    if error_list:
      self.fail(''.join(error_list))

  def _assertFieldInGroup(self, field_type, form_id, group):
    for f in getattr(self.portal, form_id).get_fields_in_group(group):
      if f.meta_type == 'ProxyField':
        if f.getRecursiveTemplateField().meta_type == field_type:
          break
      if f.meta_type == field_type:
        break
    else:
      self.fail('No %s found in %s (%s group)' % (field_type, form_id, group))

  def test_skin_selection(self):
    self.assertTrue(self.skin in
              self.portal.portal_skins.getSkinSelections())

  def test_form_list(self):
    response = self.publish(
                   '/%s/person_module/PersonModule_viewPersonList'
                    % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_list_domain_tree(self):
    self.portal.portal_selections.setListboxDisplayMode(
                  self.portal.REQUEST, 'DomainTreeMode',
                  'person_module_selection')
    # XXX no proper API on selection / selection tool for this ?
    self.portal.portal_selections.setSelectionParamsFor(
                  selection_name='person_module_selection',
                  params=dict(domain_path='portal_categories',
                              domain_url='group',
                              domain_list=()))
    response = self.publish(
                   '/%s/person_module/PersonModule_viewPersonList'
                    % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view(self):
    # form_view on a form without listbox
    self.portal.person_module.pers.setDefaultAddressZipCode(59000)
    response = self.publish(
        '/%s/person_module/pers/default_address/GeographicAddress_view'
        % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_empty_listbox(self):
    # form_view on a form with an empty listbox
    if hasattr(self.portal.person_module.pers, 'default_address'):
      self.portal.person_module.pers._delObject('default_address')
    response = self.publish(
                   '/%s/person_module/pers/Person_view'
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_non_empty_listbox(self):
    self.portal.person_module.pers.setDefaultAddressZipCode(59000)
    response = self.publish(
                   '/%s/person_module/pers/Person_view'
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_empty_format(self):
    # empty format= does not use oood for conversion
    response = self.publish(
                   '/%s/person_module/pers/Person_view?format='
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_pdf_format(self):
    # format=pdf uses oood for conversion
    response = self.publish(
                   '/%s/person_module/pers/Person_view?format=pdf'
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertEqual(content_type, 'application/pdf')
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])

  def test_form_view_html_format(self):
    # format=html is rendered inline
    response = self.publish(
                   '/%s/person_module/pers/Person_view?format=html'
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertEqual(content_type, 'text/html; charset=utf-8')
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('inline', content_disposition.split(';')[0])

  def test_report_view_form_view(self):
    # Test report view rendering forms using form_view
    self.assertEqual('form_view', self.portal.Base_viewWorkflowHistory.pt)
    response = self.publish(
                   '/%s/person_module/pers/Base_viewHistory'
                    % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_report_view_form_list(self):
    # Test report view rendering forms using form_list
    self.portal.Base_viewWorkflowHistory.pt = 'form_list'
    try:
      # publish commits a transaction, so we have to restore the original page
      # template on the form
      response = self.publish(
                   '/%s/person_module/pers/Base_viewHistory'
                    % self.portal.getId(), self.auth)
    finally:
      self.portal.Base_viewWorkflowHistory.pt = 'form_view'
      self.commit()
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())


  def test_report_view_landscape(self):
    response = self.publish(
       '/%s/person_module/pers/Base_viewHistory?landscape=1'
        % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_report_view_sheet_per_report_section(self):
    response = self.publish(
       '/%s/person_module/pers/Base_viewHistory?sheet_per_report_section=1'
        % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_encoding(self):
    self.portal.person_module.pers.setFirstName('Jérome')
    response = self.publish('/%s/person_module/pers/Person_view'
                          % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_category(self):
    self.portal.person_module.pers.setGender('male')
    response = self.publish('/%s/person_module/pers/Person_view'
                          % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_broken_category(self):
    self.portal.person_module.pers.setGender('not exist')
    self.portal.person_module.pers.setCareerRole('not exist')
    response = self.publish('/%s/person_module/pers/Person_view'
                          % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_view_embedded_image(self):
    # with image
    response = self.publish('/%s/person_module/pers/Person_viewDetails'
                          % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())
    # without image
    response = self.publish('/%s/person_module/pers_without_image/Person_viewDetails'
                          % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_report_view_encoding(self):
    self.portal.person_module.pers.setFirstName('Jérome')
    response = self.publish('/%s/person_module/pers/Base_viewHistory'
                          % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_form_list_encoding(self):
    self.portal.person_module.pers.setFirstName('Jérome')
    response = self.publish(
       '/%s/person_module/PersonModule_viewPersonList'
        % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_image_field_form_view(self):
    self._assertFieldInGroup('ImageField', 'Image_view', 'right')
    response = self.publish(
       '/%s/person_module/pers/img/Image_view'
        % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_image_field_form_view_bottom_group(self):
    self._assertFieldInGroup(
        'ImageField', 'Image_viewFullSizedImage', 'bottom')
    response = self.publish(
       '/%s/person_module/pers/img/Image_viewFullSizedImage'
        % self.portal.getId(), basic=self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    self._validate(response.getBody())

  def test_textarea_center_group(self):
    self._assertFieldInGroup('TextAreaField', 'Person_view', 'center')
    self.assert_('my_description' in [f.getId() for f in
        self.portal.Person_view.get_fields_in_group('center')])
    self.portal.person_module.pers.setDescription('<Escape>&\nnewline')
    response = self.publish(
                   '/%s/person_module/pers/Person_view'
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    body = response.getBody()
    self._validate(body)

    if self.skin == 'ODT':
      # Is it good to do this only for ODT ?
      from Products.ERP5OOo.OOoUtils import OOoParser
      parser = OOoParser()
      parser.openFromString(body)
      content_xml = parser.oo_files['content.xml']
      self.assert_('&lt;Escape&gt;&amp;<text:line-break/>newline' in content_xml)

  def test_untranslatable_columns(self):
    self.portal.ListBoxZuite_reset()
    self.portal.Localizer = DummyLocalizer()
    message_catalog = self.portal.Localizer.erp5_ui
    # XXX odt style does not seem to display a listbox if it is empty ???
    self.portal.foo_module.newContent(portal_type='Foo')
    message = self.id()
    self.portal.FooModule_viewFooList.listbox.ListBox_setPropertyList(
      field_columns = ['do_not_translate | %s' % message,],
      field_untranslatablecolumns = ['do_not_translate | %s' % message,],
    )
    self.tic()
    self.portal.changeSkin(self.skin)
    response = self.publish(
                   '/%s/foo_module/FooModule_viewFooList?portal_skin='
                   % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertTrue(content_type.startswith(self.content_type), content_type)
    content_disposition = response.getHeader('content-disposition')
    self.assertEqual('attachment', content_disposition.split(';')[0])
    body = response.getBody()
    self._validate(body)

    from Products.ERP5OOo.OOoUtils import OOoParser
    parser = OOoParser()
    parser.openFromString(body)
    content_xml = parser.oo_files['content.xml']
    self.assertTrue(message in content_xml)

    # This untranslatable column have not been translated
    self.assertTrue(message not in message_catalog._translated)

  def test_form_view_ZMI(self):
    """We can edit form_view in the ZMI."""
    response = self.publish('/%s/form_view/manage_main'
       % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertEquals('text/html;charset=UTF-8', content_type)
    self.assertFalse(response.getHeader('content-disposition'))
    # Simplistic assertion that we are viewing the ODF XML source
    self.assertTrue('office:document-content' in response.getBody())

  def test_form_list_ZMI(self):
    """We can edit form_list in the ZMI."""
    response = self.publish('/%s/form_list/manage_main'
       % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertEquals('text/html;charset=UTF-8', content_type)
    self.assertFalse(response.getHeader('content-disposition'))
    self.assertTrue('office:document-content' in response.getBody())

  def test_report_view_ZMI(self):
    """We can edit report_view in the ZMI."""
    response = self.publish('/%s/report_view/manage_main'
       % self.portal.getId(), self.auth)
    self.assertEqual(HTTP_OK, response.getStatus())
    content_type = response.getHeader('content-type')
    self.assertEquals('text/html;charset=UTF-8', content_type)
    self.assertFalse(response.getHeader('content-disposition'))
    self.assertTrue('office:document-content' in response.getBody())
class TestOooDynamicStyle(ERP5TypeTestCase):
  manager_username = '******'
  manager_password = '******'
  content_type_writer = 'application/vnd.oasis.opendocument.text'
  content = "<office:document-content xmlns:draw='urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0' xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0' xmlns:ooo='http://openoffice.org/2004/office' xmlns:number='urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0' xmlns:table='urn:oasis:names:tc:opendocument:xmlns:table:1.0' xmlns:dr3d='urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0' xmlns:fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0' xmlns:style='urn:oasis:names:tc:opendocument:xmlns:style:1.0' xmlns:xforms='http://www.w3.org/2002/xforms' xmlns:form='urn:oasis:names:tc:opendocument:xmlns:form:1.0' xmlns:script='urn:oasis:names:tc:opendocument:xmlns:script:1.0' xmlns:ooow='http://openoffice.org/2004/writer' xmlns:svg='urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0' xmlns:chart='urn:oasis:names:tc:opendocument:xmlns:chart:1.0' xmlns:dom='http://www.w3.org/2001/xml-events' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:oooc='http://openoffice.org/2004/calc' xmlns:math='http://www.w3.org/1998/Math/MathML' xmlns:tal='http://xml.zope.org/namespaces/tal' office:version='1.2'><office:scripts /><office:font-face-decls /><office:automatic-styles /><office:body><office:text /></office:body></office:document-content>"

  def getTitle(self):
    return "TestOOoDynamicStyle"

  def getBusinessTemplateList(self):
    return ('erp5_base',)

  def afterSetUp(self):
    self.login()
    self.getPortal().Localizer = DummyLocalizer()
    v12schema_url = os.path.join(os.path.dirname(__file__),
                                 'OpenDocument-schema-v1.2-draft9.rng') 
    self.validator = Validator(schema_url=v12schema_url)
    en_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_en.odt')
    en_file = open(en_file_path, 'rb')
    ja_file_path = os.path.join(os.path.dirname(__file__),
                                'test_document',
                                'DYNAMIC_STYLE_ja.odt')
    ja_file = open(ja_file_path, 'rb')

    addStyleSheet = self.getPortal().manage_addProduct['OFSP'].manage_addFile
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_en', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_en', file=en_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Test_getODTStyleSheet_ja', None) is None:
      addStyleSheet(id='Test_getODTStyleSheet_ja', file=ja_file, title='',
        precondition='', content_type=self.content_type_writer)
    if getattr(self.getPortal(), 'Base_getODTStyleSheetByLanguage', None) is None:
      script_body = """
current_language = context.Localizer.get_selected_language()
return getattr(context, "%s_%s" % (parameter, current_language))
"""
      dispatcher = self.getPortal().manage_addProduct['PythonScripts']
      dispatcher.manage_addPythonScript('Base_getODTStyleSheetByLanguage')
      script = self.getPortal().Base_getODTStyleSheetByLanguage
      script.ZPythonScript_edit('parameter', script_body)

  def _validate(self, odf_file_data):
    error_list = self.validator.validate(odf_file_data)
    if error_list:
      self.fail(''.join(error_list))

  def test_01_dynamic(self):
    """
    Test applying stylesheet dynamically, using a Python Script with
    a stylesheet file name parameter.
    """
    request = self.app.REQUEST
    addOOoTemplate = self.getPortal().manage_addProduct['ERP5OOo'].addOOoTemplate
    addOOoTemplate(id='Dynamic_viewAsOdt', title='')
    Dynamic_viewAsOdt = self.getPortal().Dynamic_viewAsOdt
    # The stylesheet file 'Test_getODTStyleSheet' is not exist in this site.
    # So, the 'Base_getODTStyleSheet', a python script creates dynamically 
    # exsited stylesheet file name. 
    self.assertFalse(self.getPortal().hasObject('Test_getODTStyleSheet'))
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_ja'))
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_en'))
    Dynamic_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                 ooo_stylesheet='Test_getODTStyleSheet', 
                                 script_name='Base_getODTStyleSheetByLanguage')
    Dynamic_viewAsOdt.pt_edit(self.content, content_type='application/vnd.oasis.opendocument.text')

    # 1. test a normal case, language: ja
    self.getPortal().Localizer.changeLanguage('ja')
    response = self.publish('/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
    self.assertEqual('application/vnd.oasis.opendocument.text',
                     response.getHeader('content-type').split(';')[0])
    self.assertEqual('attachment; filename="Dynamic_viewAsOdt.odt"',
                     response.getHeader('content-disposition'))
    self._validate(response.getBody()) 
    self.assertTrue(200, response.getStatus())

    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(len(styles_xml_body) > 0)
    # 'Style sheet ja' text is in the odt document header, 
    # and the header is in the 'styles.xml'.
    self.assertTrue(styles_xml_body.find('Style sheet ja') > 0)

    # 2. test a normal case, change the language to 'en', 
    #    so that the stylesheet changes dynamically.
    self.getPortal().Localizer = DummyLocalizer()
    self.getPortal().Localizer.changeLanguage('en')
    response = self.publish('/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
    self._validate(response.getBody()) 
    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(styles_xml_body.find('Style sheet en') > 0)

    # 3. test a fail case, reset a not existed stylesheet
    Dynamic_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                 ooo_stylesheet='NotFound_getODTStyleSheet', 
                                 script_name='Base_getODTStyleSheet')
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet'))
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet_ja'))
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet_en'))
    self.getPortal().Localizer.changeLanguage('en')
    response = self.publish('/' + self.getPortal().Dynamic_viewAsOdt.absolute_url(1))
    # then, it is not a zip stream 
    self.assertFalse(response.getBody().startswith('PK'))
    self.assertTrue(500, response.getStatus())
   

  def test_02_static(self):
    """
    Test applying stylesheet statically, using a stylesheet File object.
    """
    request = self.app.REQUEST
    addOOoTemplate = self.getPortal().manage_addProduct['ERP5OOo'].addOOoTemplate
    addOOoTemplate(id='Static_viewAsOdt', title='')
    Static_viewAsOdt = self.getPortal().Static_viewAsOdt
    # Test_getODTStyleSheet_ja is statically exist.
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_ja'))
    Static_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='Test_getODTStyleSheet_ja', script_name='')
    Static_viewAsOdt.pt_edit(self.content, content_type='application/vnd.oasis.opendocument.text')

    # 1. test a normal case
    response = self.publish('/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
    self.assertTrue(200, response.getStatus())
    self.assertEqual('application/vnd.oasis.opendocument.text',
                     response.getHeader('content-type').split(';')[0])
    self.assertEqual('attachment; filename="Static_viewAsOdt.odt"',
                     response.getHeader('content-disposition'))
    self._validate(response.getBody()) 
    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(len(styles_xml_body) > 0)
    self.assertTrue(styles_xml_body.find('Style sheet ja') > 0)

    # 2. test a normal case, change the style sheet
    self.assertTrue(self.getPortal().hasObject('Test_getODTStyleSheet_en'))
    Static_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='Test_getODTStyleSheet_en', script_name='')
    response = self.publish('/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
    self.assertTrue(200, response.getStatus())
    self._validate(response.getBody()) 
    ooo_builder = OOoBuilder(response.getBody())
    styles_xml_body = ooo_builder.extract('styles.xml')
    self.assertTrue(len(styles_xml_body) > 0)
    self.assertTrue(styles_xml_body.find('Style sheet en') > 0)

    # 3. test a fail case
    self.assertFalse(self.getPortal().hasObject('NotFound_getODTStyleSheet'))
    Static_viewAsOdt.doSettings(request, title='', xml_file_id='content.xml',
                                ooo_stylesheet='NotFound_getODTStyleSheet', script_name='')
    response = self.publish('/' + self.getPortal().Static_viewAsOdt.absolute_url(1))
    self.assertFalse(response.getBody().startswith('PK'))
    self.assertTrue(500, response.getStatus())