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

31
import transaction
32
import MethodObject
33 34

from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
35
from Products.ERP5Type.tests.utils import to_utf8
36
from Products.ERP5Type.Utils import getMessageIdWithContext
37
from zLOG import LOG
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

# dependency order
target_business_templates = (
  'erp5_base',
  'erp5_trade',

  'erp5_pdf_editor',
  'erp5_pdf_style',
  'erp5_pdm',
  'erp5_accounting',
  'erp5_invoicing',

  'erp5_apparel',

##   'erp5_banking_core',
##   'erp5_banking_cash',
##   'erp5_banking_check',
##   'erp5_banking_inventory',

  'erp5_budget',
  'erp5_public_accounting_budget',

  'erp5_consulting',

  'erp5_ingestion',
  'erp5_ingestion_mysql_innodb_catalog',
  'erp5_crm',

  'erp5_web',
  'erp5_dms',

69 70
  'erp5_commerce',

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  'erp5_forge',

  'erp5_immobilisation',

  'erp5_item',

  'erp5_mrp',

  'erp5_payroll',

  'erp5_project',

  'erp5_calendar',

  'erp5_l10n_fr',
  'erp5_l10n_ja',
  'erp5_l10n_pl_PL',
  'erp5_l10n_pt-BR',
)

91
class TestWorkflowStateTitleTranslation(ERP5TypeTestCase):
92 93 94 95 96 97 98 99 100 101 102 103
  run_all_test = 1
  domain = 'erp5_ui'
  lang = 'en'

  def getTitle(self):
    return "Translation Test"

  def getBusinessTemplateList(self):
    """  """
    return target_business_templates

  def getTranslation(self, msgid):
104

105 106 107 108
    result = self.portal.Localizer.erp5_ui.gettext(
          msgid, default='')
    #result = self.portal.Localizer.translate(
        #domain=self.domain, msgid=msgid, lang=self.lang)
109
    if (result == msgid) and (self.lang != 'en'):
110 111 112
      #result = None
      result = self.portal.Localizer.erp5_ui.gettext(msgid)
    return result.encode('utf8')
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

  def logMessage(self, message):
    self.message += '%s\n' % message

  def checkWorkflowStateTitle(self, quiet=0, run=run_all_test):
    """
    Test workflow state title translation.
    Check that using portal_catalog can not return strange results to the user.
    Each translation must be only related to one state ID.
    """
    if not run: return
    self.message = '\n'

    translation_dict = {}

    workflow_tool = self.portal.portal_workflow
    for workflow_id in workflow_tool.objectIds():
      workflow = workflow_tool._getOb(workflow_id)
      class_name = workflow.__class__.__name__
      if class_name == 'DCWorkflowDefinition':
        for state in workflow.states.items():
          state_title = state[1].title
          state_id = state[0]
136
          msgid = getMessageIdWithContext(state_title, 'state', workflow_id)
137
          translated_state_title = self.getTranslation(msgid)
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

          if translated_state_title is not None:
            if translation_dict.has_key(translated_state_title):
              translation_dict[translated_state_title].add(state_id)
            else:
              translation_dict[translated_state_title] = set([state_id])


    for key, value in translation_dict.items():
      if len(value) == 1:
        translation_dict.pop(key)

    if translation_dict != {}:
      # State ID has multiple translation associated, and it leads to
      # unexpected results for the user when using portal catalog.
      rejected_key_list = translation_dict.keys()
      result_dict = dict([(x, []) for x in rejected_key_list])
      error_dict =  dict([(x, []) for x in rejected_key_list])
      error = 0

      # Browse all workflows to ease fixing this issue.
      for workflow in self.portal.portal_workflow.objectValues():
        if workflow.__class__.__name__ == 'DCWorkflowDefinition':
          workflow_id = workflow.id
          workflow_dict = {}
          for state_id, state in workflow.states._mapping.items():
            state_title = state.title
            translated_state_title = \
              self.portal.Localizer.erp5_ui.gettext(state_title, lang=self.lang)
            if translated_state_title in rejected_key_list:
              result_dict[translated_state_title].append(
                  (workflow_id, state_id, state_title))

      # XXX To be improved
      not_used_workflow_id_list = []
      for key, item_list in result_dict.items():
        wrong_state_id_list = [x[1] for x in item_list]
        for workflow_id, wrong_state_id, state_title in item_list:
          if workflow_id not in not_used_workflow_id_list:
            workflow = self.portal.portal_workflow._getOb(workflow_id)
            state_id_list = []
            for state_id in workflow.states._mapping.keys():
              if (state_id in wrong_state_id_list) and \
                  (state_id != wrong_state_id):
                state_id_list.append(state_id)

            if len(state_id_list) != 0:
              error_dict[key].append((
                workflow_id, wrong_state_id, state_title, state_id_list))
              error = 1
188

189 190 191
      if error:
        for key, item_list in error_dict.items():
          if len(item_list) != 0:
192
            self.logMessage("\n'%s'" % key.encode('utf-8'))
193
            self.logMessage('\t### Conflicting workflow with common states (ie, what user can see) ###')
194 195 196
            for item in item_list:
              # XXX Improve rendering
              self.logMessage(
197
                  "\t%r\t%r\t'%s'\t%r" % \
198
                  item)
199
            self.logMessage('\n\t### All conflicting workflows (ie, problems asking to happen) ###')
200 201 202
            for item in result_dict[key]:
              # XXX Improve rendering
              self.logMessage(
203
                  "\t%r\t%r\t'%s'" % \
204
                  item)
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        self.fail(self.message)

  def test_01_EnglishTranslation(self, quiet=0, run=run_all_test):
    """
    Test English translation
    """
    self.lang = 'en'
    self.checkWorkflowStateTitle(quiet=quiet, run=run)

  def test_02_FrenchTranslation(self, quiet=0, run=run_all_test):
    """
    Test French translation
    """
    self.lang = 'fr'
    self.checkWorkflowStateTitle(quiet=quiet, run=run)

  def test_03_JapaneseTranslation(self, quiet=0, run=run_all_test):
    """
    Test Japanese translation
    """
    self.lang = 'ja'
    self.checkWorkflowStateTitle(quiet=quiet, run=run)

  def test_04_PolishTranslation(self, quiet=0, run=run_all_test):
    """
    Test Polish translation
    """
    self.lang = 'pl'
    self.checkWorkflowStateTitle(quiet=quiet, run=run)

  def test_05_PortugueseTranslation(self, quiet=0, run=run_all_test):
    """
    Test Portuguese translation
    """
    self.lang = 'pt-BR'
    self.checkWorkflowStateTitle(quiet=quiet, run=run)
242

243 244 245 246 247 248
  def test_06_FrenchTranslationOfMessageWithContext(self, quiet=0,
         run=run_all_test):
    """
    Test French translation
    """
    self.lang = 'fr'
249

250 251
    message_catalog = self.portal.Localizer.erp5_ui
    message_catalog.gettext('Validated', add=1)
252 253 254 255 256 257 258 259 260 261 262
    message_catalog.gettext('Draft', add=1)
    message_catalog.gettext(getMessageIdWithContext('Validated',
                                                    'state',
                                                    'item_workflow'),
                            add=1)
    message_catalog.message_edit('Validated', self.lang,
                                 'Validé'.decode('utf8'), '')
    message_catalog.message_edit(getMessageIdWithContext('Validated',
                                                         'state',
                                                         'item_workflow'),
                                 self.lang, "En bon usage", '')
263
    message_catalog.message_edit('Draft', self.lang, '', '')
264 265
    portal_type = 'Organisation'
    organisation_module = self.getPortal().getDefaultModule(portal_type)
266
    organisation = organisation_module.newContent(
267 268
                  portal_type=portal_type,
                  title='My Organisation')
269
    organisation.validate()
270 271 272
    portal_type = 'Item'
    item_module = self.getPortal().getDefaultModule(portal_type)
    item = item_module.newContent(portal_type=portal_type, title='Lot A')
273 274 275 276

    transaction.commit()
    self.tic()
    self.portal.Localizer.get_selected_language = lambda: self.lang
277

278
    self.assertEquals(item.getTranslatedValidationStateTitle(), 'Draft')
279
    item.validate()
280 281 282
    self.assertEquals(item.getTranslatedValidationStateTitle(), "En bon usage")
    self.assertEquals(organisation.getTranslatedValidationStateTitle(),
                      'Validé')
283 284 285 286 287 288
    # Now run indexation of translations.
    self.portal.ERP5Site_updateTranslationTable()
    # Ckeck queries with translated workflow state title generated with
    # getMessageIdWithContext
    self.assertTrue(len(self.portal.portal_catalog(
                            translated_validation_state_title="En bon usage")))
289

290 291 292 293 294 295 296 297 298
class LanguageGetter(MethodObject.Method):

  def __init__(self, lang):
    self.lang = lang

  def __call__(self, context):
    return self.lang

class TestTranslation(ERP5TypeTestCase):
299

300 301
  lang = 'fr'

302 303 304
  def getTitle(self):
    return 'Test Translation'

305 306 307
  def getBusinessTemplateList(self):
    return ['erp5_base',]

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  def _setUpTranslations(self):
    self.portal.Localizer.manage_addLanguage(self.lang)
    erp5_ui = self.portal.Localizer.erp5_ui
    erp5_ui.gettext('Draft', add=1)
    erp5_ui.gettext('Person', add=1)
    erp5_ui.message_edit('Draft', self.lang, 'Brouillon', '')
    erp5_ui.message_edit('Person', self.lang, 'Personne', '')
    self.portal.ERP5Site_updateTranslationTable()

  def _cleanUpTranslations(self):
    erp5_ui = self.portal.Localizer.erp5_ui
    for msgid in ('Person', 'Draft'):
      translations = erp5_ui.get_translations(msgid)
      translations.pop(self.lang, None)
    self.portal.ERP5Site_updateTranslationTable()

  def afterSetUp(self):
    ERP5TypeTestCase.afterSetUp(self)
    self._setUpTranslations()
327

328 329 330 331 332 333 334 335 336 337 338 339
    # replace Localizer.utils.lang_negotiator in MessageCatalog to return
    # self.lang
    from Products.Localizer import MessageCatalog
    self.old_lang_negotiator = MessageCatalog.lang_negotiator
    def lang_negotiator(avilable_languages, self=self):
      return self.lang
    MessageCatalog.lang_negotiator = lang_negotiator

    # patch get_selected_language, used by portal_catalog queries that use
    # translation
    self.portal.Localizer.get_selected_language = LanguageGetter(self.lang)

340 341 342 343
    # create the zpt used by self.translate_by_zpt()
    dispatcher = self.portal.manage_addProduct['PageTemplates']
    dispatcher.manage_addPageTemplate('myzpt')
    self.myzpt = self.portal.myzpt
344 345
    self.stepTic()

346
  def beforeTearDown(self):
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    transaction.abort()
    # unpatch lang_negotiator and get_selected_message
    from Products.Localizer import MessageCatalog
    MessageCatalog.lang_negotiator = self.old_lang_negotiator
    del self.portal.Localizer.get_selected_language

    self._cleanUpTranslations()
    # test clean-up actually worked
    erp5_ui = self.portal.Localizer.erp5_ui
    self.assertEquals(erp5_ui.gettext('Person', lang=self.lang), 'Person')
    self.assertEquals(erp5_ui.gettext('Draft', lang=self.lang), 'Draft')

    # erase created objects
    for module in (self.portal.person_module, self.portal.organisation_module):
      module.manage_delObjects(list(module.objectIds()))
362 363
    self.portal.manage_delObjects(['myzpt'])

364
    self.stepTic()
365
    ERP5TypeTestCase.beforeTearDown(self)
366

367 368 369 370 371
  def test_Localizer_translation(self):
    # basically, test afterSetUp worked...
    erp5_ui = self.portal.Localizer.erp5_ui
    self.assertEquals(erp5_ui.gettext('Person', lang=self.lang), 'Personne')

372
  def translate_by_zpt(self, domain, *words):
373 374
    zpt_template = """
    <tal:ommit xmlns:i18n="http://xml.zope.org/namespaces/i18n"
375 376 377
               i18n:domain="%s">
      <tal:ommit repeat="word options/words" content="word"
                 i18n:translate="">Word</tal:ommit>
378
    </tal:ommit>
379 380 381 382 383 384 385 386 387 388 389 390
    """ % domain
    self.myzpt.pt_edit(zpt_template, 'text/html')
    results = to_utf8(self.myzpt(words=words)).split()
    return results

  def test_ZPT_translation(self):
    results = self.translate_by_zpt('erp5_ui', 'Person', 'Draft')
    self.assertEquals(results, ['Personne', 'Brouillon'])

  def test_ZPT_translation_with_domain_alias(self):
    # test with a translation domain alias
    results = self.translate_by_zpt('ui', 'Person', 'Draft')
391 392 393
    self.assertEquals(results, ['Personne', 'Brouillon'])

  def test_portal_type_and_state_title_translation_on_portal_catalog(self):
394 395
    # make sure we can search by "translated_validation_state_title" and
    # "translated_portal_type"
396 397 398 399 400
    person_1 = self.portal.person_module.newContent(portal_type='Person')
    person_1.validate()
    person_2 = self.portal.person_module.newContent(portal_type='Person')
    organisation = self.portal.organisation_module.newContent(
                            portal_type='Organisation')
401

402
    self.stepTic()
403 404 405
    self.assertEquals(set([person_1, person_2]),
        set([x.getObject() for x in
          self.portal.portal_catalog(translated_portal_type='Personne')]))
406

407 408 409 410 411 412 413 414 415 416 417 418
    self.assertEquals(set([person_2, organisation]),
        set([x.getObject() for x in
          self.portal.portal_catalog(translated_validation_state_title='Brouillon',
                                     portal_type=('Person', 'Organisation'))]))
    self.assertEquals([person_2],
        [x.getObject() for x in
          self.portal.portal_catalog(translated_validation_state_title='Brouillon',
                                     translated_portal_type='Personne')])

class TestTranslationWithBusinessTemplate(TestTranslation):

  def _setUpTranslations(self):
419 420
    self.manuallyInstallBusinessTemplate('erp5_l10n_fr')

421 422
  def _cleanUpTranslations(self):
    self.uninstallBusinessTemplate('erp5_l10n_fr')
423

424 425 426
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestTranslation))
427 428
  suite.addTest(unittest.makeSuite(TestTranslationWithBusinessTemplate))
  suite.addTest(unittest.makeSuite(TestWorkflowStateTitleTranslation))
429
  return suite