testXHTML.py 29.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4
##############################################################################
#
# Copyright (c) 2007 Nexedi SARL and Contributors. All Rights Reserved.
5 6
#               Fabien Morin <fabien@nexedi.com
#               Jacek Medrzycki <jacek@erp5.pl>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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.
#
##############################################################################

30 31
import unittest
import os
32
import urllib
33

Lingnan Wu's avatar
Lingnan Wu committed
34
from subprocess import Popen, PIPE
35
from Testing import ZopeTestCase
36 37
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.CMFCore.utils import getToolByName
38 39
from zLOG import LOG
from xml.dom import minidom
40 41 42 43 44 45 46
# You can invoke same tests in your favourite collection of business templates
# by using TestXHTMLMixin like the following :
#
# from Products.ERP5.tests.testERP5XHTML import TestXHTMLMixin
# class TestMyXHTML(TestXHTMLMixin):
#   def getBusinessTemplateList(self):
#     return (...)
47

48
class TestXHTMLMixin(ERP5TypeTestCase):
49

50 51
  # some forms have intentionally empty listbox selections like RSS generators
  FORM_LISTBOX_EMPTY_SELECTION_PATH_LIST = ['erp5_web_widget_library/WebSection_viewContentListAsRSS']
52
  IGNORE_FILE_LIST = ['require.js','require.min.js','wz_dragdrop.js',
53
                      'renderjs.js','jio.js','rsvp.js','handlebars.js']
54

55 56 57 58 59 60 61 62
  def changeSkin(self, skin_name):
    """
      Change current Skin
    """
    request = self.app.REQUEST
    self.getPortal().portal_skins.changeSkin(skin_name)
    request.set('portal_skin', skin_name)

63 64 65 66 67 68 69 70 71 72 73 74
  def getFieldList(self, form, form_path):
    try:
      for field in form.get_fields(include_disabled=1):
        if field.getTemplateField() is not None:
          try:
            if field.get_value('enabled'):
              yield field
          except Exception:
            yield field
    except AttributeError, e:
      ZopeTestCase._print("%s is broken: %s" % (form_path, e))

75 76 77 78
  def test_deadProxyFields(self):
    # check that all proxy fields defined in business templates have a valid
    # target
    skins_tool = self.portal.portal_skins
79
    error_list = []
80 81 82 83 84 85 86

    for skin_name, skin_folder_string in skins_tool.getSkinPaths():
      skin_folder_id_list = skin_folder_string.split(',')
      self.changeSkin(skin_name)

      for skin_folder_id in skin_folder_id_list:
        for field_path, field in skins_tool[skin_folder_id].ZopeFind(
87
                  skins_tool[skin_folder_id],
88 89 90
                  obj_metatypes=['ProxyField'], search_sub=1):
          template_field = field.getTemplateField(cache=False)
          if template_field is None:
Jérome Perrin's avatar
Jérome Perrin committed
91
            # Base_viewRelatedObjectList (used for proxy listbox ids on
92 93
            # relation fields) is an exception, the proxy field has no target
            # by default.
Jérome Perrin's avatar
Jérome Perrin committed
94
            if field_path != 'Base_viewRelatedObjectList/listbox':
95 96
              error_list.append((skin_name, field_path, field.get_value('form_id'),
                                 field.get_value('field_id')))
97 98

    if error_list:
99 100
      message = '\nDead proxy field list%s\n' \
                    % '\n\t'.join(str(e) for e in error_list)
101
      self.fail(message)
102

103 104
  def test_configurationOfFieldLibrary(self):
    error_list = []
105 106
    for business_template in self.portal.portal_templates.searchFolder(
          title=['erp5_trade']):
107 108 109
      # XXX Impossible to filter by installation state, as it is not catalogued
      business_template = business_template.getObject()
      for modifiable_field in business_template.BusinessTemplate_getModifiableFieldList():
110
        # Do not consider 'Check delegated values' as an error
111 112
        if modifiable_field.choice_item_list[0][1] not in \
            ("0_check_delegated_value", "0_keep_non_proxy_field"):
113 114
          error_list.append((modifiable_field.object_id,
                            modifiable_field.choice_item_list[0][0]))
115
    if error_list:
116
      message = '%s fields to modify' % len(error_list)
117 118 119
      message += '\n\t' + '\n\t'.join(fieldname + ": " + message
                                       for fieldname, message in error_list)
      self.fail(message)
120

121 122 123 124 125 126 127 128
  def test_portalTypesDomainTranslation(self):
    # according to bt5-Module.Creation.Guidelines document, module
    # portal_types should be translated using erp5_ui, and normal ones, using
    # erp5_content
    error_list = []
    portal_types_module = self.portal.portal_types
    for portal_type in portal_types_module.contentValues(portal_type=\
        'Base Type'):
129
      if portal_type.getId().endswith('Module'):
130
        for k, v in portal_type.getPropertyTranslationDomainDict().items():
131
          if k in ('title', 'short_title') and v.getDomainName() != 'erp5_ui':
132
            error_list.append('"%s" should use erp5_ui for %s' % \
133
                (portal_type.getId(), k))
134
    if error_list:
135 136
      message = '\nBad portal_type domain translation list%s\n' \
                    % '\n\t'.join(error_list)
137 138
      self.fail(message)

139 140 141 142 143 144
  def test_emptySelectionNameInListbox(self):
    # check all empty selection name in listboxes
    skins_tool = self.portal.portal_skins
    error_list = []
    for form_path, form in skins_tool.ZopeFind(
              skins_tool, obj_metatypes=['ERP5 Form'], search_sub=1):
145
      for field in self.getFieldList(form, form_path):
Fabien Morin's avatar
Fabien Morin committed
146
        if field.getRecursiveTemplateField().meta_type == 'ListBox':
147
          selection_name = field.get_value("selection_name")
148
          if selection_name in ("",None) and \
149
            form_path not in self.FORM_LISTBOX_EMPTY_SELECTION_PATH_LIST:
150
            error_list.append(form_path)
151
    self.assertEqual(error_list, [])
152

153
  def test_duplicatingSelectionNameInListbox(self):
154
    """
155
    Check for duplicating selection name in listboxes.
156
    Usually we should not have duplicates except in some rare cases
157 158
    described in SkinsTool_getDuplicateSelectionNameDict
    """
159 160 161 162 163
    portal_skins = self.portal.portal_skins
    duplicating_selection_name_dict = portal_skins.SkinsTool_getDuplicateSelectionNameDict()
    self.assertFalse(duplicating_selection_name_dict,
                     "Repeated listbox selection names:\n" +
                     portal_skins.SkinsTool_checkDuplicateSelectionName())
164

Lingnan Wu's avatar
Lingnan Wu committed
165 166 167 168 169 170
  def test_javascript_lint(self):
    skins_tool = self.portal.portal_skins
    path_list = []
    for script_path, script in skins_tool.ZopeFind(
              skins_tool, obj_metatypes=['File','DTML Method','DTML Document'], search_sub=1):
      is_required_check_path = True
171
      ignore_bts = ['erp5_jquery','erp5_fckeditor','erp5_xinha_editor', 'erp5_svg_editor',
172
                    'erp5_jquery_ui', 'erp5_ace_editor', 'erp5_code_mirror']
Lingnan Wu's avatar
Lingnan Wu committed
173 174
      if script_path.endswith('.js'):
        for ignore_bt_name in ignore_bts:
175
          if script_path.startswith(ignore_bt_name):
Lingnan Wu's avatar
Lingnan Wu committed
176
            is_required_check_path = False
177
        for ignore_file in self.IGNORE_FILE_LIST:
178
          if script_path.endswith(ignore_file):
Lingnan Wu's avatar
Lingnan Wu committed
179 180 181 182 183
            is_required_check_path = False
        if is_required_check_path:
          path_list.append(script_path)
    def jsl(check_path):
      body = self.publish(check_path).getBody()
184
      conf_file = os.path.join(os.path.dirname(__file__), 'jsl.conf')
Lingnan Wu's avatar
Lingnan Wu committed
185
      try:
186
        stdout, stderr = Popen(['jsl', '-stdin', '-nologo', '-nosummary', '-conf', conf_file],
Lingnan Wu's avatar
Lingnan Wu committed
187 188 189
                               stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate(body)
      except OSError, e:
        raise OSError, '%r\n%r' % (os.environ, e)
190
      self.assertEqual(stdout, '', 'jsl result of %s : %s' % (check_path, stdout))
Lingnan Wu's avatar
Lingnan Wu committed
191 192 193 194 195
    portal_skins_path = '%s/portal_skins' % self.portal.getId()
    for path in path_list:
      check_path = '%s/%s' % (portal_skins_path, path)
      jsl(check_path)

Xiaowu Zhang's avatar
Xiaowu Zhang committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

  def test_html_file(self):
    path_list = os.environ.get('CGI_PATH',
    '/usr/lib/cgi-bin:/usr/lib/cgi-bin/w3c-markup-validator').split(os.pathsep)
    for path in path_list:
      validator_path = os.path.join(path, 'check')
      if os.path.exists(validator_path):
        validator = W3Validator(validator_path, show_warnings)
        break
    if validator is not None:
      skins_tool = self.portal.portal_skins
      path_list = []
      for script_path, script in skins_tool.ZopeFind(
                skins_tool, obj_metatypes=['File'], search_sub=1):
        is_required_check_path = True
211
        ignore_bts = ['erp5_jquery','erp5_fckeditor','erp5_xinha_editor', 'erp5_svg_editor', 'erp5_jquery_ui']
Xiaowu Zhang's avatar
Xiaowu Zhang committed
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 243 244 245 246
        if script_path.endswith('.html'):
          for ignore_bt_name in ignore_bts:
            if  script_path.startswith(ignore_bt_name):
              is_required_check_path = False
              break;
          if is_required_check_path:
            path_list.append(script_path)

      def validate_html_file(source_path):
        message = ['Using %s validator to parse the file "%s"'
                   ' with warnings%sdisplayed :'
                  % (validator.name, source_path,
                     validator.show_warnings and ' ' or ' NOT ')]
        source = self.publish(source_path).getBody()
        result_list_list = validator.getErrorAndWarningList(source)
        severity_list = ['Error']
        if validator.show_warnings:
          severity_list.append('Warning')
        for i, severity in enumerate(severity_list):
          for line, column, msg in result_list_list[i]:
            if line is None and column is None:
              message.append('%s: %s' % (severity, msg))
            else:
              message.append('%s: line %s column %s : %s' %
                             (severity, line, column, msg))
        return len(message) == 1, '\n'.join(message)

      def html_file(check_path):
        self.assert_(*validate_html_file(source_path=check_path))

      portal_skins_path = '%s/portal_skins' % self.portal.getId()
      for path in path_list:
        check_path = '%s/%s' % (portal_skins_path, path)
        html_file(check_path)

Ivan Tyagov's avatar
Ivan Tyagov committed
247
  def test_PythonScriptSyntax(self):
248
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
249 250
    Check that Python Scripts syntax is correct.
    """
251 252 253 254 255
    for tool in (self.portal.portal_skins, self.portal.portal_workflow):
      for script_path, script in tool.ZopeFind(
                tool, obj_metatypes=['Script (Python)'], search_sub=1):
        if script.errors!=():
          # we need to add script id as well in test failure
256
          self.assertEqual('%s : %s' %(script_path, script.errors), ())
Ivan Tyagov's avatar
Ivan Tyagov committed
257 258

  def test_SkinItemId(self):
259
    """
Ivan Tyagov's avatar
Ivan Tyagov committed
260 261 262 263 264 265 266 267
    Check that skin item id is acquiring is correct.
    """
    skins_tool = self.portal.portal_skins
    for skin_folder in skins_tool.objectValues('Folder'):
      for skin_item in skin_folder.objectValues():
        if skin_item.meta_type not in ('File', 'Image', 'DTML Document', 'DTML Method',):
          skin_item_id = skin_item.id
          self.assertEqual(skin_item_id, skin_folder[skin_item_id].id)
268

Nicolas Delaby's avatar
Nicolas Delaby committed
269
  def test_callableListMethodInListbox(self):
270 271 272 273 274
    # check all list_method in listboxes
    skins_tool = self.portal.portal_skins
    error_list = []
    for form_path, form in skins_tool.ZopeFind(
              skins_tool, obj_metatypes=['ERP5 Form'], search_sub=1):
275
      for field in self.getFieldList(form, form_path):
Fabien Morin's avatar
Fabien Morin committed
276
        if field.getRecursiveTemplateField().meta_type == 'ListBox':
277 278 279
          list_method = field.get_value("list_method")
          if list_method:
            if isinstance(list_method, str):
280
              method = getattr(self.portal, list_method, None)
281 282 283
            else:
              method = list_method
            if not callable(method):
284
              error_list.append((form_path, list_method))
285
    self.assertEqual(error_list, [])
286

287 288 289 290 291 292 293
  def test_listActionInListbox(self):
    # check all list_action in listboxes
    skins_tool = self.portal.portal_skins
    error_list = []
    for form_path, form in skins_tool.ZopeFind(
              skins_tool, obj_metatypes=['ERP5 Form'], search_sub=1):
      for field in self.getFieldList(form, form_path):
Fabien Morin's avatar
Fabien Morin committed
294
        if field.getRecursiveTemplateField().meta_type == 'ListBox':
295 296 297 298
          list_action = field.get_value("list_action")
          if list_action and list_action != 'list': # We assume that 'list'
                                                    # list_action exists
            if isinstance(list_action, str):
299 300
              # list_action can be a fully qualified URL, we care for last part of it
              list_action = list_action.split('/')[-1].split('?')[0]
301 302 303 304
              try:
                method = self.portal.restrictedTraverse(list_action)
              except KeyError:
                method = None
305 306 307 308 309 310
              if method is None:
                # list_action can actually exists but not in current skin, check if it can be found in portal_skins
                found_list_action_list = skins_tool.ZopeFind(skins_tool, obj_ids=[list_action], search_sub=1)
                if found_list_action_list:
                  method = found_list_action_list[0][1]
                  ZopeTestCase._print("List action %s for %s is not part of current skin but do exists in another skin folder.\n" % (list_action, form_path))
311 312 313
            else:
              method = list_action
            if not callable(method):
314 315 316
              error_list.append('Form %s/%s : list_action "%s" is not callable.'\
                  % (form_path, field.id, list_action))
    self.assert_(not len(error_list), '\n'.join(error_list))
317

318 319
  def test_moduleListMethod(self):
    """Make sure that module's list method works."""
320
    error_list = []
321 322
    for document in self.portal.contentValues():
      if document.portal_type.endswith(' Module'):
323
        if document.getTranslatedTitle() not in document.list(reset=1):
324 325
          error_list.append(document.id)
    self.assertEqual([], error_list)
326

327 328 329 330
  def test_preferenceViewDuplication(self):
    """Make sure that preference view is not duplicated."""
    preference_view_id_dict = {}
    def addPreferenceView(folder_id, view_id):
Jérome Perrin's avatar
Jérome Perrin committed
331
      preference_view_id_dict.setdefault(view_id, []).append('%s.%s' % (folder_id, view_id))
332
    error_list = []
Jérome Perrin's avatar
Jérome Perrin committed
333 334
    for skin_folder in self.portal.portal_skins.objectValues():
      if skin_folder.isPrincipiaFolderish:
335
        for id_ in skin_folder.objectIds():
336
          if id_.startswith('Preference_view'):
Jérome Perrin's avatar
Jérome Perrin committed
337
            addPreferenceView(skin_folder.id, id_)
338
    for view_id, location_list in preference_view_id_dict.items():
Jérome Perrin's avatar
Jérome Perrin committed
339
      if len(location_list) > 1:
340 341 342
        error_list.extend(location_list)
    self.assertEqual(error_list, [])

343 344 345 346 347 348 349 350 351 352 353 354 355 356
class TestXHTML(TestXHTMLMixin):

  run_all_test = 1

  def getTitle(self):
    return "XHTML Test"

  @staticmethod
  def getBusinessTemplateList():
    """  """
    return ( # dependency order
      'erp5_core_proxy_field_legacy',
      'erp5_base',
      'erp5_simulation',
357
      'erp5_pdm',
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
      '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_jquery',
      'erp5_jquery_ui',
      'erp5_web',
      'erp5_dms',
      'erp5_email_reader',
      'erp5_commerce',
      'erp5_credential',
387
      'erp5_test_result',
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

      'erp5_forge',

      'erp5_immobilisation',

      'erp5_item',

      'erp5_mrp',

      'erp5_payroll',

      'erp5_project',

      'erp5_calendar',

      'erp5_advanced_invoicing',

      'erp5_odt_style',

      'erp5_administration',

      'erp5_knowledge_pad',
      'erp5_knowledge_pad_ui_test',
      'erp5_km',
      'erp5_ui_test',
      'erp5_dms_ui_test',

      'erp5_trade_proxy_field_legacy', # it is necessary until all bt are well
                                       # reviewed. Many bt like erp5_project are
                                       # using obsolete field library of trade
      'erp5_xhtml_style',
      'erp5_jquery_plugin_svg_editor',
      'erp5_jquery_plugin_spinbtn',
      'erp5_jquery_plugin_jquerybbq',
      'erp5_jquery_plugin_svgicon',
      'erp5_jquery_plugin_jgraduate',
      'erp5_jquery_plugin_hotkey',
      'erp5_jquery_plugin_elastic',
      'erp5_jquery_plugin_colorpicker',
      'erp5_jquery_plugin_jqchart',
      'erp5_jquery_plugin_sheet',
      'erp5_jquery_plugin_mbmenu',
      'erp5_jquery_plugin_wdcalendar',
      'erp5_xinha_editor',
      'erp5_svg_editor',
      'erp5_jquery_sheet_editor',
      'erp5_web_ung_core',
      'erp5_web_ung_theme',
      'erp5_web_ung_role',
      'erp5_ui_test',
      'erp5_web_ung_ui_test',
      'erp5_l10n_fr', # install at least one localization business template
                      # because some language switching widgets are only
                      # present if there is more than one available language.
    )

  def afterSetUp(self):
    self.portal = self.getPortal()

    uf = self.getPortal().acl_users
    uf._doAddUser('seb', '', ['Manager'], [])

    self.login('seb')
    self.enableDefaultSitePreference()

  def enableDefaultSitePreference(self):
    portal_preferences = getToolByName(self.portal, 'portal_preferences')
    default_site_preference = portal_preferences.default_site_preference
    if self.portal.portal_workflow.isTransitionPossible(default_site_preference, 'enable'):
      default_site_preference.enable()

459 460 461 462 463 464 465 466 467 468 469 470
class W3Validator(object):

  def __init__(self, validator_path, show_warnings):
    self.validator_path = validator_path
    self.show_warnings = show_warnings
    self.name = 'w3c'

  def _parse_validation_results(self, result):
    """
    parses the validation results, returns a list of tuples:
    line_number, col_number, error description
    """
471
    result_list_list = []
472 473 474 475 476 477
    try:
      xml_doc = minidom.parseString(result)
    except:
      import sys
      print >> sys.stderr, "Could not parse result:\n%s" % result
      raise
478 479 480 481
    for severity in 'm:error', 'm:warning':
      result_list = []
      for error in xml_doc.getElementsByTagName(severity):
        result = []
482 483 484 485 486 487

        # Ignore warning about using direct input mode (W28)
        messageid_list = error.getElementsByTagName('m:messageid')
        if messageid_list and messageid_list[0].firstChild.nodeValue == 'W28':
          continue

488 489 490 491 492 493 494 495 496
        for name in 'm:line', 'm:col', 'm:message':
          element_list = error.getElementsByTagName(name)
          if element_list:
            result.append(element_list[0].firstChild.nodeValue)
          else:
            result.append(None)
        result_list.append(tuple(result))
      result_list_list.append(result_list)
    return result_list_list
497 498 499 500 501

  def getErrorAndWarningList(self, page_source):
    '''
      retrun two list : a list of errors and an other for warnings
    '''
502 503
    source = 'fragment=%s&output=soap12' % urllib.quote_plus(
      page_source.encode('utf-8'))
504 505 506 507 508 509 510
    stdout, stderr = Popen(self.validator_path,
            stdin=PIPE, stdout=PIPE, stderr=PIPE,
            close_fds=True,
            env={"CONTENT_LENGTH": str(len(source)),
                 "REQUEST_METHOD": "POST"}).communicate(source)
    # Output is a set of headers then the XML content.
    return self._parse_validation_results(
511
      stdout.split('\n\n', 1)[1])
512 513 514 515


class TidyValidator(object):

Jérome Perrin's avatar
Jérome Perrin committed
516
  def __init__(self, validator_path, show_warnings):
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    self.validator_path = validator_path
    self.show_warnings = show_warnings
    self.name = 'tidy'

  def _parse_validation_results(self, result):
    """
    parses the validation results, returns a list of tuples:
    line_number, col_number, error description
    """
    error_list=[]
    warning_list=[]

    for i in result:
      data = i.split(' - ')
      if len(data) >= 2:
        data[1] = data[1].replace('\n','')
        if data[1].startswith('Error: '):
          location_list = data[0].split(' ')
          line = location_list[1]
          column = location_list[3]
          message = data[1].split(': ')[1]
          error_list.append((line, column, message))
        elif data[1].startswith('Warning: '):
          location_list = data[0].split(' ')
          line = location_list[1]
          column = location_list[3]
          message = data[1].split(': ')[1]
          warning_list.append((line, column, message))
    return (error_list, warning_list)

  def getErrorAndWarningList(self, page_source):
    '''
      retrun two list : a list of errors and an other for warnings
    '''
551 552 553
    stdout, stderr = Popen('%s -e -q -utf8' % self.validator_path,
            stdin=PIPE, stdout=PIPE, stderr=PIPE,
            close_fds=True).communicate(page_source)
554 555 556 557 558 559 560
    return self._parse_validation_results(stderr)


def validate_xhtml(validator, source, view_name, bt_name):
  '''
    validate_xhtml return True if there is no error on the page, False else.
    Now it's possible to show warnings, so, if the option is set to True on the
561
    validator object, and there is some warning on the page, the function
562 563 564
    return False, even if there is no error.
  '''
  # display some information when test faild to facilitate debugging
565
  message = ['Using %s validator to parse the view "%s" (from %s bt)'
Julien Muchembled's avatar
typo  
Julien Muchembled committed
566
             ' with warnings%sdisplayed :'
567
             % (validator.name, view_name, bt_name,
Julien Muchembled's avatar
typo  
Julien Muchembled committed
568
                validator.show_warnings and ' ' or ' NOT ')]
569

570
  result_list_list = validator.getErrorAndWarningList(source)
571

572 573 574
  severity_list = ['Error']
  if validator.show_warnings:
    severity_list.append('Warning')
575

576 577 578 579 580 581 582
  for i, severity in enumerate(severity_list):
    for line, column, msg in result_list_list[i]:
      if line is None and column is None:
        message.append('%s: %s' % (severity, msg))
      else:
        message.append('%s: line %s column %s : %s' %
                       (severity, line, column, msg))
583

584
  return len(message) == 1, '\n'.join(message)
585 586 587 588 589


def makeTestMethod(validator, module_id, portal_type, view_name, bt_name):

  def createSubContent(content, portal_type_list):
Jérome Perrin's avatar
Jérome Perrin committed
590
    if not portal_type_list:
591
      return content
Jérome Perrin's avatar
Jérome Perrin committed
592 593 594 595 596
    if portal_type_list == [content.getPortalType()]:
      return content
    return createSubContent(
               content.newContent(portal_type=portal_type_list[0]),
               portal_type_list[1:])
597

598 599
  def testMethod(self):
    module = getattr(self.portal, module_id)
600 601 602 603
    portal_type_list = portal_type.split('/')

    object = createSubContent(module, portal_type_list)
    view = getattr(object, view_name)
604 605 606
    self.assert_(*validate_xhtml( validator=validator,
                                  source=view(),
                                  view_name=view_name,
607
                                  bt_name=bt_name))
608 609
  return testMethod

610 611 612
def testPortalTypeViewRecursivly(test_class, validator, module_id,
    business_template_info, business_template_info_list, portal_type_list,
    portal_type_path_dict, base_path, tested_portal_type_list):
613
  '''
614
  This function go on all portal_type recursivly if the portal_type could
615 616 617 618 619 620 621 622
  contain other portal_types and make a test for all view that have action
  '''
  # iteration over all allowed portal_types inside the module/portal_type
  for portal_type in portal_type_list:
    portal_path = portal_type_path_dict[portal_type]
    if portal_type not in tested_portal_type_list:
      # this portal type haven't been tested yet

623
      backuped_module_id = module_id
624 625 626 627 628 629 630 631 632 633 634 635 636 637
      backuped_business_template_info = business_template_info

      if not business_template_info.actions.has_key(portal_type):
        # search in other bt :
        business_template_info = None
        for bt_info in business_template_info_list:
          if bt_info.actions.has_key(portal_type):
            business_template_info = bt_info
            break
        if not business_template_info:
          LOG("Can't find the action :", 0, portal_type)
          break
        # create the object in portal_trash module
        module_id = 'portal_trash'
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
      for business_template_info in business_template_info_list:
        if portal_type not in business_template_info.actions:
          continue
        for action_information in business_template_info.actions[portal_type]:
          if (action_information['category'] in ('object_view', 'object_list') and
              action_information['visible']==1 and
              action_information['action'].startswith('string:${object_url}/') and
              len(action_information['action'].split('/'))==2):
            view_name = action_information['action'].split('/')[-1].split('?')[0]
            method = makeTestMethod(validator,
                                    module_id,
                                    portal_path,
                                    view_name,
                                    business_template_info.title)
            method_name = ('test_%s_%s_%s' %
                          (business_template_info.title,
                            str(portal_type).replace(' ','_'), # can be unicode
                            view_name))
            method.__name__ = method_name
            setattr(test_class, method_name, method)
            module_id = backuped_module_id
659 660 661 662 663

      # add the portal_type to the tested portal_types. This avoid to test many
      # times a Portal Type wich is many bt.
      tested_portal_type_list.append(portal_type)

664 665 666
      new_portal_type_list = []
      for tmp_business_template_info in business_template_info_list:
        new_portal_type_list.extend(tmp_business_template_info.allowed_content_types.get(portal_type, ()))
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
      new_portal_type_path_dict = {}

      if base_path != '':
        next_base_path = '%s/%s' % (base_path, portal_type)
      # Module portal_type not to have been added to the path because
      # this portal type object already existing
      elif 'Module' not in portal_type:
        next_base_path = portal_type
      else:
        next_base_path = ''

      for pt in new_portal_type_list:
        if next_base_path != '' and 'Module' not in pt:
          new_portal_type_path_dict[pt] = '%s/%s' % (next_base_path, pt)
        else:
682
          new_portal_type_path_dict[pt] = pt
683 684
      testPortalTypeViewRecursivly(test_class=test_class,
                       validator=validator,
685 686
                       module_id=module_id,
                       business_template_info=backuped_business_template_info,
687
                       business_template_info_list=business_template_info_list,
688
                       portal_type_list=new_portal_type_list,
689 690 691 692
                       portal_type_path_dict=new_portal_type_path_dict,
                       base_path=next_base_path,
                       tested_portal_type_list=tested_portal_type_list)

693
def addTestMethodDynamically(test_class, validator, target_business_templates):
694 695
  from Products.ERP5.tests.utils import BusinessTemplateInfoTar
  from Products.ERP5.tests.utils import BusinessTemplateInfoDir
696 697
  business_template_info_list = []

698 699 700
  for url, _ in ERP5TypeTestCase._getBTPathAndIdList(target_business_templates):
    if os.path.isdir(url):
      business_template_info = BusinessTemplateInfoDir(url)
701
    else:
702 703
      business_template_info = BusinessTemplateInfoTar(url)
    business_template_info_list.append(business_template_info)
704

705 706
  tested_portal_type_list = []
  for business_template_info in business_template_info_list:
707
    for module_id, module_portal_type in business_template_info.modules.items():
Jérome Perrin's avatar
Jérome Perrin committed
708
      portal_type_list = [module_portal_type, ] + \
709
            business_template_info.allowed_content_types.get(module_portal_type, [])
710
      portal_type_path_dict = dict(zip(portal_type_list, portal_type_list))
711 712
      testPortalTypeViewRecursivly(test_class=test_class,
                       validator=validator,
713 714
                       module_id=module_id,
                       business_template_info=business_template_info,
715
                       business_template_info_list=business_template_info_list,
716
                       portal_type_list=portal_type_list,
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
                       portal_type_path_dict=portal_type_path_dict,
                       base_path = '',
                       tested_portal_type_list=tested_portal_type_list)


# Two validators are available : tidy and the w3c validator
# It's hightly recommanded to use the w3c validator because tidy dont show
# all errors and show more warnings that there is.
validator_to_use = 'w3c'
show_warnings = True

validator = None

# tidy or w3c may not be installed in livecd. Then we will skip xhtml validation tests.
# create the validator object
if validator_to_use == 'w3c':
733 734
  validator_path_list = os.environ.get('CGI_PATH',
    '/usr/lib/cgi-bin:/usr/lib/cgi-bin/w3c-markup-validator').split(os.pathsep)
735
  for path in validator_path_list:
736
    validator_path = os.path.join(path, 'check')
737 738 739
    if os.path.exists(validator_path):
      validator = W3Validator(validator_path, show_warnings)
      break
740
  else:
741
    print 'No w3c validator found at', validator_path_list
742

Jérome Perrin's avatar
Jérome Perrin committed
743
elif validator_to_use == 'tidy':
744 745 746 747 748 749 750 751
  error = False
  warning = False
  validator_path = '/usr/bin/tidy'
  if not os.path.exists(validator_path):
    print 'tidy is not installed at %s' % validator_path
  else:
    validator = TidyValidator(validator_path, show_warnings)

752
def test_suite():
753
  # add the tests
754 755 756
  if validator is not None:
    # add erp5_core to the list here to not return it
    # on getBusinessTemplateList call
757
    addTestMethodDynamically(TestXHTML, validator,
758
      ('erp5_core',) + TestXHTML.getBusinessTemplateList())
759 760 761
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestXHTML))
  return suite