testTranslation.py 17.3 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 MethodObject
32 33

from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
34
from Products.ERP5Type.Utils import getMessageIdWithContext
35 36 37 38

# dependency order
target_business_templates = (
  'erp5_base',
39
  'erp5_simulation',
40
  'erp5_pdm',
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
  'erp5_trade',

  'erp5_pdf_editor',
  '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',

66 67
  'erp5_commerce',

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  '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',
)

88
class TestWorkflowStateTitleTranslation(ERP5TypeTestCase):
89 90 91 92 93 94 95 96 97 98 99 100
  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):
101

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

  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]
Nicolas Delaby's avatar
Nicolas Delaby committed
133
          msgid = getMessageIdWithContext(state_title, 'state', workflow_id)
134
          translated_state_title = self.getTranslation(msgid)
135 136

          if translated_state_title is not None:
137
            try:
138
              translation_dict[translated_state_title].add(state_id)
139 140
            except KeyError:
              translation_dict[translated_state_title] = {state_id}
141 142 143 144 145 146 147 148 149 150


    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()
151 152
      result_dict = {x: [] for x in rejected_key_list}
      error_dict =  {x: [] for x in rejected_key_list}
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
      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
185

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

203 204
        self.fail(self.message)

205 206 207 208
  def afterSetUp(self):
    self.portal.Localizer._default_language = 'en'
    self.portal.Localizer.set_languages(['en', 'fr'])

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 242
  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)
243

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

251 252
    message_catalog = self.portal.Localizer.erp5_ui
    message_catalog.gettext('Validated', add=1)
253 254 255 256 257 258 259 260 261 262 263
    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", '')
264
    message_catalog.message_edit('Draft', self.lang, '', '')
265 266
    portal_type = 'Organisation'
    organisation_module = self.getPortal().getDefaultModule(portal_type)
267
    organisation = organisation_module.newContent(
268 269
                  portal_type=portal_type,
                  title='My Organisation')
270
    organisation.validate()
271 272 273
    portal_type = 'Item'
    item_module = self.getPortal().getDefaultModule(portal_type)
    item = item_module.newContent(portal_type=portal_type, title='Lot A')
274 275

    self.tic()
276
    self.portal.Localizer._default_language = 'fr'
277

278
    self.assertEqual(item.getTranslatedValidationStateTitle(), 'Draft')
279
    item.validate()
280 281
    self.assertEqual(item.getTranslatedValidationStateTitle(), "En bon usage")
    self.assertEqual(organisation.getTranslatedValidationStateTitle(),
282
                      'Validé')
283 284
    # Now run indexation of translations.
    self.portal.ERP5Site_updateTranslationTable()
285
    self.tic()
286 287
    # Ckeck queries with translated workflow state title generated with
    # getMessageIdWithContext
288
    self.assertEqual(1, len(self.portal.portal_catalog(
289
      translated_validation_state_title="En bon usage")))
290
    self.assertEqual(1, len(self.portal.portal_catalog(
291
      translated_validation_state_title="En bon usage", portal_type='Item')))
292
    self.assertEqual(0, len(self.portal.portal_catalog(
293 294
      translated_validation_state_title="En bon usage",
      portal_type='Organisation')))
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  def test_07_NegatedQueryForTranslation(self, quiet=0, run=run_all_test):
    """
    Check that catalog search with a negated query parameter doesn't return
    unexpected results.
     - get a portal type ans its related workflow
     - add a new context translation for the original state
     - update the catalog tables
     - verify the catalog result
    """
    self.lang = 'en'
    # Get one portal type and its related workflow
    portal_type_id = 'Bug'
    workflow_id = 'bug_workflow'
    assert(workflow_id in \
            self.portal.portal_workflow.getChainFor(portal_type_id))
    bug = self.portal.getDefaultModule(portal_type_id).newContent(
        portal_type=portal_type_id)
    state_title = bug.getSimulationStateTitle()

    # add a new context translation for the original state
    message_catalog = self.portal.Localizer.erp5_ui
    message_catalog.gettext(state_title, add=1)
    message_catalog.gettext(getMessageIdWithContext(state_title,
                                                    'state',
                                                    workflow_id),
                            add=1)
    assert(bug.getTranslatedSimulationStateTitle() == state_title)

    try:
      message_catalog.message_edit(getMessageIdWithContext(state_title,
                                                           'state',
                                                           workflow_id),
                                   self.lang, "%s in context" % state_title, '')
      assert(bug.getTranslatedSimulationStateTitle() == \
                                    "%s in context" % state_title)

      # Update the translation table
      self.portal.ERP5Site_updateTranslationTable()
      self.tic()

      # Check the catalog result
      assert(len(self.portal.portal_catalog(portal_type=portal_type_id)) == 1)
      result = self.portal.portal_catalog(portal_type=portal_type_id,
          translated_simulation_state_title='!="%s in context"' % state_title)
340
      self.assertEqual(len(result), 0)
341 342 343 344 345 346 347 348 349
    finally:
      # Clean the new context message
      message_catalog.message_del(getMessageIdWithContext(state_title,
                                                      'state',
                                                      workflow_id))
      # Update the translation table
      self.portal.ERP5Site_updateTranslationTable()
      self.tic()

350 351 352 353 354 355 356 357 358
class LanguageGetter(MethodObject.Method):

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

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

class TestTranslation(ERP5TypeTestCase):
359

360 361
  lang = 'fr'

362 363 364
  def getTitle(self):
    return 'Test Translation'

365 366 367
  def getBusinessTemplateList(self):
    return ['erp5_base',]

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  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):
385
    super(TestTranslation, self).afterSetUp()
386
    self._setUpTranslations()
387

388 389 390 391 392 393 394 395 396 397 398 399
    # 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)

400 401 402 403
    # create the zpt used by self.translate_by_zpt()
    dispatcher = self.portal.manage_addProduct['PageTemplates']
    dispatcher.manage_addPageTemplate('myzpt')
    self.myzpt = self.portal.myzpt
404
    self.tic()
405

406
  def beforeTearDown(self):
407
    self.abort()
408 409 410 411 412 413 414 415
    # 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
416 417
    self.assertEqual(erp5_ui.gettext('Person', lang=self.lang), 'Person')
    self.assertEqual(erp5_ui.gettext('Draft', lang=self.lang), 'Draft')
418 419 420 421

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

424
    self.tic()
425
    super(TestTranslation, self).beforeTearDown()
426

427 428 429
  def test_Localizer_translation(self):
    # basically, test afterSetUp worked...
    erp5_ui = self.portal.Localizer.erp5_ui
430
    self.assertEqual(erp5_ui.gettext('Person', lang=self.lang), 'Personne')
431

432
  def translate_by_zpt(self, domain, *words):
433 434
    zpt_template = """
    <tal:ommit xmlns:i18n="http://xml.zope.org/namespaces/i18n"
435 436 437
               i18n:domain="%s">
      <tal:ommit repeat="word options/words" content="word"
                 i18n:translate="">Word</tal:ommit>
438
    </tal:ommit>
439 440
    """ % domain
    self.myzpt.pt_edit(zpt_template, 'text/html')
441
    return self.myzpt(words=words).encode('utf-8').split()
442 443 444

  def test_ZPT_translation(self):
    results = self.translate_by_zpt('erp5_ui', 'Person', 'Draft')
445
    self.assertEqual(results, ['Personne', 'Brouillon'])
446 447 448 449

  def test_ZPT_translation_with_domain_alias(self):
    # test with a translation domain alias
    results = self.translate_by_zpt('ui', 'Person', 'Draft')
450
    self.assertEqual(results, ['Personne', 'Brouillon'])
451 452

  def test_portal_type_and_state_title_translation_on_portal_catalog(self):
453 454
    # make sure we can search by "translated_validation_state_title" and
    # "translated_portal_type"
455 456 457 458 459
    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')
460

461
    self.tic()
462 463
    self.assertEqual({person_1, person_2}, {x.getObject() for x in
          self.portal.portal_catalog(translated_portal_type='Personne')})
464

465
    self.assertEqual({person_2, organisation}, {x.getObject() for x in
466
          self.portal.portal_catalog(translated_validation_state_title='Brouillon',
467
                                     portal_type=('Person', 'Organisation'))})
468
    self.assertEqual([person_2],
469 470 471 472 473 474 475
        [x.getObject() for x in
          self.portal.portal_catalog(translated_validation_state_title='Brouillon',
                                     translated_portal_type='Personne')])

class TestTranslationWithBusinessTemplate(TestTranslation):

  def _setUpTranslations(self):
476 477
    self.manuallyInstallBusinessTemplate('erp5_l10n_fr')

478 479
  def _cleanUpTranslations(self):
    self.uninstallBusinessTemplate('erp5_l10n_fr')
480

481 482 483
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestTranslation))
484 485
  suite.addTest(unittest.makeSuite(TestTranslationWithBusinessTemplate))
  suite.addTest(unittest.makeSuite(TestWorkflowStateTitleTranslation))
486
  return suite