testOOoImport.py 39 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
##############################################################################
3 4
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
#                    Mohamadou Mbengue <mmbengue@gmail.com>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# 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.
#
##############################################################################


Jérome Perrin's avatar
Jérome Perrin committed
30
import unittest
31
import os
32

33 34
from AccessControl.SecurityManagement import newSecurityManager
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
Jérome Perrin's avatar
Jérome Perrin committed
35
from Products.ERP5Type.tests.ERP5TypeTestCase import _getConversionServerDict
36
from Products.ERP5Type.tests.utils import FileUpload
37
from Products.ERP5Type.tests.Sequence import SequenceList
38
from Products.ERP5OOo.OOoUtils import OOoParser
Jérome Perrin's avatar
Jérome Perrin committed
39
from Products.ERP5Form.PreferenceTool import Priority
40 41
from DateTime import DateTime

42
def makeFilePath(name):
43
  return os.path.join(os.path.dirname(__file__), 'test_document', name)
44 45 46

def makeFileUpload(name):
  path = makeFilePath(name)
47
  return FileUpload(path, name)
48

49
class TestOOoImportMixin(ERP5TypeTestCase):
50 51
  gender_base_cat_id    = 'gender'
  function_base_cat_id  = 'function'
52

Jérome Perrin's avatar
Jérome Perrin committed
53
  def afterSetUp(self):
54 55 56 57
    """
      Initialize the ERP5 site.
    """
    self.login()
58
    self.pref = self.portal.portal_preferences.newContent(
59
                          portal_type='System Preference')
Jérome Perrin's avatar
Jérome Perrin committed
60
    conversion_dict = _getConversionServerDict()
61
    self.pref.setPreferredDocumentConversionServerUrl(conversion_dict['url'])
Jérome Perrin's avatar
Jérome Perrin committed
62 63
    self.pref.setPriority(Priority.SITE)
    self.pref.enable()
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    # create browser_id_manager
    if not "browser_id_manager" in self.portal.objectIds():
      self.portal.manage_addProduct['Sessions'].constructBrowserIdManager()

    # We create categories needed
    # For testing file whith column corresponding to category
    portal_categories = self.getCategoryTool()

    gender_bc = self.gender_base_cat_id
    if gender_bc not in portal_categories.objectIds():
      portal_categories.newContent(portal_type='Base Category', id=gender_bc)
    if not portal_categories[gender_bc].has_key('male'):
      portal_categories[gender_bc].newContent(id='male', portal_type='Category', title='Male')
    if not portal_categories[gender_bc].has_key('female'):
      portal_categories[gender_bc].newContent(id='female', portal_type='Category', title='Female')

    function_bc = self.function_base_cat_id
    if function_bc not in portal_categories.objectIds():
      portal_categories.newContent(portal_type='Base Category', id=function_bc)
    if not portal_categories[function_bc].has_key('director'):
      portal_categories[function_bc].newContent(id='director', portal_type='Category', title='Director')
    if not portal_categories[function_bc].has_key('manager'):
      portal_categories[function_bc].newContent(id='manager', portal_type='Category', title='Manager')

89
    self.portal.portal_caches.clearCache()
90 91 92
    self.tic()

  def beforeTearDown(self):
93
    self.tic()
94
    for parent in [
95 96 97
        self.portal.currency_module,
        self.portal.organisation_module,
        self.portal.person_module,
98
        self.portal.portal_categories.function,
Łukasz Nowak's avatar
Łukasz Nowak committed
99 100
        self.portal.portal_categories.gender,
        self.portal.portal_categories.region,
101 102
        ]:
      parent.deleteContent(list(parent.objectIds()))
103
    self.portal.portal_preferences.manage_delObjects([self.pref.getId()])
104

105 106
    self.tic()

107
class TestOOoImport(TestOOoImportMixin):
108 109 110
  """
    ERP5  test import object list from OOo Document
  """
111 112

  ##################################
113
  ##  ZopeTestCase Skeleton
114 115
  ##################################

116
  def getTitle(self):
117
    """
118
      Return the title of the current test set.
119
    """
120 121 122 123 124 125 126
    return "ERP5 Site - OOo File importing"

  def getBusinessTemplateList(self):
    """
      Return the list of required business templates.
    """
    return ('erp5_base', 'erp5_ooo_import')
127 128 129 130 131

  ##################################
  ##  Basic steps
  ##################################
  def stepImportRawDataFile(self, sequence=None, sequence_list=None, **kw):
Nicolas Delaby's avatar
Nicolas Delaby committed
132
    f = makeFileUpload('import_data_list.ods')
133 134 135 136 137 138 139 140 141 142 143
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.last_name'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.default_email_text'}
    )
144
    person_module.Base_importFile(import_file=f, listbox=listbox)
Nicolas Delaby's avatar
Nicolas Delaby committed
145

146
  def stepCheckActivitiesCount(self, sequence=None, sequence_list=None, **kw):
147 148 149 150 151
    message_list   = self.getPortal().portal_activities.getMessageList()
    self.assertEqual(102,len(message_list))
    '''for i in range(101):
      method_id = message_list[i].method_id
      self.assertEqual('Base_importFileLine',method_id)'''
Nicolas Delaby's avatar
Nicolas Delaby committed
152

153 154
  def stepCheckImportedPersonList(self, sequence=None, sequence_list=None,
                                  num=101, **kw):
155
    person_list = self.getPortal().person_module.objectValues()
156 157 158 159 160 161 162 163 164 165 166 167
    self.assertEqual(
      sorted(['John Doe %s' % (i) for i in range(num)]),
      sorted([person_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted(['John' for i in range(num)]),
      sorted([person_list[i].getFirstName() for i in range(num)]))
    self.assertEqual(
      sorted(['Doe %s' % (i) for i in range(num)]),
      sorted([person_list[i].getLastName() for i in range(num)]))
    self.assertEqual(
      sorted(['john.doe%s@foo.com' % (i) for i in range(num)]),
      sorted([person_list[i].getDefaultEmailText() for i in range(num)]))
168

169
  def stepCheckImportedPersonListBlank(self, sequence=None, sequence_list=None, **kw):
170 171
    return self.stepCheckImportedPersonList(sequence=sequence,
                                            sequence_list=sequence_list, **kw)
172 173

  def stepCheckImportedPersonListCategory(self, sequence=None, sequence_list=None, **kw):
174
    num = 10
175
    person_list = self.getPortal().person_module.objectValues()
176
    self.assertEqual(
177
      ['John'] * num,
178 179 180 181 182 183 184 185 186 187
      sorted([person_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted(['John' for i in range(num)]),
      sorted([person_list[i].getFirstName() for i in range(num)]))
    self.assertEqual(
      sorted(['male' for i in range(num)]),
      sorted([person_list[i].getGender() for i in range(num)]))
    self.assertEqual(
      sorted(['director' for i in range(num)]),
      sorted([person_list[i].getFunction() for i in range(num)]))
188 189 190 191 192 193
    self.assertEqual(
      sorted(['europe/france' for i in range(num)]),
      sorted([person_list[i].getRegion() for i in range(num)]))
    self.assertEqual(
      sorted(['France' for i in range(num)]),
      sorted([person_list[i].getRegionTitle() for i in range(num)]))
194 195

  def stepCheckAuthorImportedPersonList(self, sequence=None, sequence_list=None, **kw):
196 197 198
    return self.stepCheckImportedPersonListCategory(sequence=sequence,
                                                    sequence_list=sequence_list,
                                                    **kw)
199 200

  def stepCheckImportedPersonListFreeText(self, sequence=None, sequence_list=None, **kw):
201
    num = 10
202
    person_list = self.getPortal().person_module.objectValues()
203
    self.assertEqual(
204
      ['John'] * num,
205 206 207 208 209 210 211 212 213 214
      sorted([person_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted(['John' for i in range(num)]),
      sorted([person_list[i].getFirstName() for i in range(num)]))
    self.assertEqual(
      sorted(['male' for i in range(num)]),
      sorted([person_list[i].getGenderFreeText() for i in range(num)]))
    self.assertEqual(
      sorted(['Director' for i in range(num)]),
      sorted([person_list[i].getFunctionFreeText() for i in range(num)]))
215 216

  def stepCheckImportedPersonListAccentuated(self, sequence=None, sequence_list=None, **kw):
217
    num = 10
218
    person_list = self.getPortal().person_module.objectValues()
219
    self.assertEqual(
220
      ['John'] * num,
221 222 223 224 225 226 227 228 229 230
      sorted([person_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted(['John' for i in range(num)]),
      sorted([person_list[i].getFirstName() for i in range(num)]))
    self.assertEqual(
      sorted(['male' for i in range(num)]),
      sorted([person_list[i].getGender() for i in range(num)]))
    self.assertEqual(
      sorted(['director' for i in range(num)]),
      sorted([person_list[i].getFunction() for i in range(num)]))
231 232

  def stepCheckXLSImportedPersonList(self, sequence=None, sequence_list=None, **kw):
233 234 235
    return self.stepCheckImportedPersonList(sequence=sequence,
                                            sequence_list=sequence_list,
                                            num=10, **kw)
236 237

  def stepCheckImportedPersonListWithDates(self, sequence=None, sequence_list=None, **kw):
238
    num = 10
239
    person_list = self.getPortal().person_module.objectValues()
240
    self.assertEqual(
241
      ['John'] * num,
242 243 244 245 246 247 248 249 250 251
      sorted([person_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted(['John' for i in range(num)]),
      sorted([person_list[i].getFirstName() for i in range(num)]))
    self.assertEqual(
      sorted(['male' for i in range(num)]),
      sorted([person_list[i].getGender() for i in range(num)]))
    self.assertEqual(
      sorted([DateTime('2008/02/%02d %s' % (i+1, 'GMT')) for i in range(num)]),
      sorted([person_list[i].getStartDate() for i in range(num)]))
252 253

  def stepCheckImportFloatsAndPercentage(self, sequence=None, sequence_list=None, **kw):
254
    num = 10
255
    currency_module = self.getPortal().currency_module
256 257 258 259 260 261 262 263
    currency_list = [currency_module[str(i + 1)] \
                   for i in range(num)]
    self.assertEqual(
      sorted(['Currency %s' % (i) for i in range(num)]),
      sorted([currency_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted([1000.3 + i for i in range(num)]),
      sorted([currency_list[i].getHeightQuantity() for i in range(num)]))
264 265

  def stepCheckImportedPersonList_1(self, sequence=None, sequence_list=None, **kw):
266 267 268
    return self.stepCheckImportedPersonList(sequence=sequence,
                                            sequence_list=sequence_list,
                                            num=1000, **kw)
269 270

  def stepCheckImportedPersonList_2(self, sequence=None, sequence_list=None, **kw):
271 272 273
    return self.stepCheckImportedPersonList(sequence=sequence,
                                            sequence_list=sequence_list,
                                            num=10000, **kw)
274 275

  def stepCheckImportedOrganisationList(self, sequence=None, sequence_list=None, **kw):
276
    num = 10
277
    organisation_module = self.getPortal().organisation_module
278 279 280 281 282 283 284 285 286 287 288 289 290 291
    organisation_list = [organisation_module[str(i + 1)] \
                   for i in range(num)]
    self.assertEqual(
      sorted(['Foo Organisation %s' % (i) for i in range(num)]),
      sorted([organisation_list[i].getTitle() for i in range(num)]))
    self.assertEqual(
      sorted(['Description organisation %s' % (i) for i in range(num)]),
      sorted([organisation_list[i].getDescription() for i in range(num)]))
    self.assertEqual(
      sorted(['+(0)-1234567%s' % i for i in range(num)]),
      sorted([organisation_list[i].getTelephoneText() for i in range(num)]))
    self.assertEqual(
      sorted(['org%s@foo.com' % i for i in range(num)]),
      sorted([organisation_list[i].getEmailText() for i in range(num)]))
292 293 294 295 296

  def stepImportFileNoMapping(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_list.ods')

    person_module = self.getPortal().person_module
297 298 299 300 301 302 303 304 305 306 307 308
    listbox = (
    { 'listbox_key': '001',
      'portal_type_property_list': ''},
    { 'listbox_key': '002',
      'portal_type_property_list': ''},
    { 'listbox_key': '003',
      'portal_type_property_list': ''},
    { 'listbox_key': '004',
      'portal_type_property_list': ''},)
    redirect = person_module.Base_importFile(import_file=f, listbox=listbox)
    self.assertTrue(redirect.endswith(
      'portal_status_message=Please%20Define%20a%20mapping.'))
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

  def stepImportFileWithBlankLine(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_list_blank_line.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.last_name'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.default_email_text'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportFileWithCategory(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_with_categories.ods')
327 328 329 330 331 332 333 334 335
    # create some regions
    region = self.portal.portal_categories.region
    europe = region.newContent(portal_type='Category',
                      title='Europe',
                      id='europe')
    europe.newContent(portal_type='Category',
                      title='France',
                      id='france')

336 337 338 339 340 341 342 343 344
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.gender'},
    { 'listbox_key': '004',
345 346 347
      'portal_type_property_list':'Person.function'},
    { 'listbox_key': '005',
      'portal_type_property_list':'Person.region'}
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportFileWithDates(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_with_dates.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.gender'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.start_date'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)
365

366
  def stepImportFloatsAndPercentage(self, sequence=None, sequence_list=None, **kw):
367
    """
368 369
      This test make sure that either floats (1000,9), sientific numbers (1,00E+003)
      or percentage (19%) are correctly imported .
370
    """
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    f = makeFileUpload('import_float_and_percentage.ods')
    currency_module = self.getPortal().currency_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Currency.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Currency.height_quantity'}
    )
    currency_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportOrganisation(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_organisation_list.ods')
    organisation_module = self.getPortal().organisation_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Organisation.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Organisation.description'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Organisation.telephone_text'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Organisation.email_text'}
    )
    organisation_module.Base_importFile(import_file=f, listbox=listbox)

  def stepAuthorImportFile(self, sequence=None, sequence_list=None, **kw):
Jérome Perrin's avatar
Jérome Perrin committed
397 398 399 400 401 402 403 404 405
    # create some regions
    region = self.portal.portal_categories.region
    europe = region.newContent(portal_type='Category',
                      title='Europe',
                      id='europe')
    europe.newContent(portal_type='Category',
                      title='France',
                      id='france')

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    user_name = 'author'
    user_folder = self.portal.acl_users
    user_folder._doAddUser(user_name, '', ['Author', 'Member'], [])
    user = user_folder.getUserById(user_name).__of__(user_folder)
    newSecurityManager(None, user)

    f = makeFileUpload('import_data_with_categories.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.gender'},
    { 'listbox_key': '004',
Jérome Perrin's avatar
Jérome Perrin committed
422 423 424
      'portal_type_property_list':'Person.function'},
    { 'listbox_key': '005',
      'portal_type_property_list':'Person.region'}
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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportFileWithFreeText(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_with_categories.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.gender_free_text'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.function_free_text'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportFileWithAccentuatedText(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_accentuated_text.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.gender'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.function'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportXLSFile(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_list.xls')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.last_name'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.default_email_text'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportBigFile_1(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_big_file_1.ods')
    person_module = self.getPortal().person_module
    listbox=(
    { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.last_name'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.default_email_text'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  def stepImportBigFile_2(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_big_file_2.ods')
    person_module = self.getPortal().person_module
    listbox=(
     { 'listbox_key': '001',
      'portal_type_property_list':'Person.title'},
    { 'listbox_key': '002',
      'portal_type_property_list':'Person.first_name'},
    { 'listbox_key': '003',
      'portal_type_property_list':'Person.last_name'},
    { 'listbox_key': '004',
      'portal_type_property_list':'Person.default_email_text'}
    )
    person_module.Base_importFile(import_file=f, listbox=listbox)

  ##  Tests
  ##################################
505
  def test_01_ImportFileLine(self):
506
    # Simulate import of OOo file Base_importFile for Person Module.
507 508 509 510 511 512 513 514
    sequence_list = SequenceList()
    step_list = [ 'stepImportRawDataFile'
                 ,'stepCheckActivitiesCount'
                 ,'Tic'
                 ,'stepCheckImportedPersonList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
515
    sequence_list.play(self)
516

517
  def test_02_ImportFileBlankLine(self):
518 519 520 521 522 523 524 525
    #Simulate import of an OOo file with blank lines.
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithBlankLine'
                  ,'Tic'
                  ,'stepCheckImportedPersonListBlank'
                 ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
526
    sequence_list.play(self)
527

528
  def test_03_ImportNoMapping(self):
529 530 531 532 533
    sequence_list = SequenceList()
    step_list = [ 'stepImportFileNoMapping'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
534
    sequence_list.play(self)
535

536
  def test_04_ImportFileWithCategory(self):
537 538 539 540 541 542 543
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithCategory'
                  ,'Tic'
                  ,'stepCheckImportedPersonListCategory'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
544
    sequence_list.play(self)
545

546
  def test_05_ImportOrganisation(self):
547 548 549 550 551 552 553
    sequence_list = SequenceList()
    step_list = [  'stepImportOrganisation'
                  ,'Tic'
                  ,'stepCheckImportedOrganisationList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
554
    sequence_list.play(self)
555

556
  def test_06_AuthorImportFile(self):
557 558 559 560 561 562 563
    sequence_list = SequenceList()
    step_list = [  'stepAuthorImportFile'
                  ,'Tic'
                  ,'stepCheckAuthorImportedPersonList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
564
    sequence_list.play(self)
565

566
  def test_07_ImportFileWithFreeText(self):
567 568 569 570 571 572 573
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithFreeText'
                  ,'Tic'
                  ,'stepCheckImportedPersonListFreeText'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
574
    sequence_list.play(self)
575

576
  def test_08_ImportFileWithAccentuatedText(self):
577 578 579 580 581 582 583
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithAccentuatedText'
                  ,'Tic'
                  ,'stepCheckImportedPersonListAccentuated'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
584
    sequence_list.play(self)
585

586
  def test_09_ImportXLSFile(self):
587 588 589 590 591 592 593
    sequence_list = SequenceList()
    step_list = [ 'stepImportXLSFile'
                 ,'Tic'
                 ,'stepCheckXLSImportedPersonList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
594
    sequence_list.play(self)
595

596
  def test_10_ImportFileWithDates(self):
597 598 599 600 601 602 603
    sequence_list = SequenceList()
    step_list = [ 'stepImportFileWithDates'
                 ,'Tic'
                 ,'stepCheckImportedPersonListWithDates'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
604
    sequence_list.play(self)
605

606
  def test_11_ImportFloatAndPercentage(self):
607 608 609 610 611 612 613
    sequence_list = SequenceList()
    step_list = [ 'stepImportFloatsAndPercentage'
                 ,'Tic'
                 ,'stepCheckImportFloatsAndPercentage'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
614
    sequence_list.play(self)
615

616
  def test_12_ImportBigFile_1(self):
617 618 619 620 621 622 623
    sequence_list = SequenceList()
    step_list = [  'stepImportBigFile_1'
                  ,'Tic'
                  ,'stepCheckImportedPersonList_1'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
624
    sequence_list.play(self)
625

626 627 628 629 630 631 632 633 634
#  def test_12_ImportBigFile_2(self):
#    sequence_list = SequenceList()
#    step_list = [  'stepImportBigFile_2'
#                  ,'Tic'
#                  ,'stepCheckImportedPersonList_2'
#                ]
#    sequence_string = ' '.join(step_list)
#    sequence_list.addSequenceString(sequence_string)
#    sequence_list.play(self)
635

636
  # CategoryTool_importCategoryFile tests
637 638 639 640 641 642 643 644 645 646 647
  def test_CategoryTool_importCategoryFile(self):
    # tests simple use of CategoryTool_importCategoryFile script
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category.sxc'))
    self.tic()
    region = self.portal.portal_categories.region
    self.assertEqual(2, len(region))
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
648
    self.assertEqual('France', france.getTitle())
649
    self.assertTrue(france.hasProperty('title'))
650 651 652
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
653 654 655 656

  def test_CategoryTool_importCategoryFileDeletionSupport(self):
    # tests simple use of CategoryTool_importCategoryFile script
    region = self.portal.portal_categories.region
Łukasz Nowak's avatar
Łukasz Nowak committed
657
    region.newContent(id='dummy_region')
658 659 660 661 662 663 664 665 666 667
    self.tic()
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category.sxc'),
        existing_category_list='delete')
    self.tic()
    self.assertEqual(2, len(region))
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
668
    self.assertEqual('France', france.getTitle())
669
    self.assertTrue(france.hasProperty('title'))
670 671 672
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
673 674 675 676

  def test_CategoryTool_importCategoryFileExpirationSupport(self):
    # tests simple use of CategoryTool_importCategoryFile script
    region = self.portal.portal_categories.region
Łukasz Nowak's avatar
Łukasz Nowak committed
677
    region.newContent(id='dummy_region')
678 679 680 681 682 683 684 685 686 687 688
    self.tic()
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category.sxc'),
        existing_category_list='expire')
    self.tic()
    self.assertEqual(3, len(region))
    self.assertTrue('dummy_region' in region.objectIds())
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
689
    self.assertEqual('France', france.getTitle())
690
    self.assertTrue(france.hasProperty('title'))
691 692 693
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
694

695 696 697 698 699 700 701 702 703 704 705
  def test_CategoryTool_importCategoryFileXLS(self):
    # tests that CategoryTool_importCategoryFile supports .xls files
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category.xls'))
    self.tic()
    region = self.portal.portal_categories.region
    self.assertEqual(2, len(region))
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
706 707 708 709
    self.assertEqual('France', france.getTitle())
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
710

711 712 713 714 715 716 717 718 719 720 721
  def test_CategoryTool_importCategoryFile_PathStars(self):
    # tests CategoryTool_importCategoryFile with * in the paths columns
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category_path_stars.sxc'))
    self.tic()
    region = self.portal.portal_categories.region
    self.assertEqual(2, len(region))
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
722 723 724 725
    self.assertEqual('France', france.getTitle())
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
726

727 728 729 730 731 732 733 734 735 736 737 738 739
  def test_CategoryTool_importCategoryFile_PathStars_noID(self):
    # tests CategoryTool_importCategoryFile with * in the paths columns, and no
    # ID column, and non ascii titles
    self.portal.portal_categories.CategoryTool_importCategoryFile(
            import_file=makeFileUpload(
              'import_region_category_path_stars_non_ascii.sxc'))
    self.tic()
    region = self.portal.portal_categories.region
    self.assertEqual(2, len(region))
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
740 741 742 743
    self.assertEqual('Frànce', france.getTitle())
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
744 745 746 747 748 749 750 751 752 753

  def test_CategoryTool_importCategoryFile_DuplicateIds(self):
    # tests CategoryTool_importCategoryFile when a document contain same
    # categories ID at different level (a good candidate for an acquisition
    # bug)
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category_duplicate_ids.sxc'))
    self.tic()
    region = self.portal.portal_categories.region
    self.assertEqual(1, len(region))
754 755 756 757 758
    self.assertEqual(['europe'], list(region.objectIds()))
    self.assertEqual(['france'], list(region.europe.objectIds()))
    self.assertEqual(['europe'], list(region.europe.france.objectIds()))
    self.assertEqual(['france'], list(region.europe.france.europe.objectIds()))
    self.assertEqual([], list(region.europe.france.europe.france.objectIds()))
759

760 761 762 763 764 765
  # Base_getCategoriesSpreadSheetMapping tests
  def test_Base_getCategoriesSpreadSheetMapping(self):
    # test structure returned by Base_getCategoriesSpreadSheetMapping
    mapping = self.portal.Base_getCategoriesSpreadSheetMapping(
        import_file=makeFileUpload('import_region_category.sxc'))
    self.assertTrue(isinstance(mapping, dict))
766
    self.assertEqual(['region'], list(mapping.keys()))
767 768
    region = mapping['region']
    self.assertTrue(isinstance(region, list))
769
    self.assertEqual(6, len(region))
770
    # base category is contained in the list
771
    self.assertEqual(dict(path='region',
772 773
                           title='region'),
                      region[0])
774
    self.assertEqual(dict(path='region/europe',
775
                           short_title='Europe',
776 777
                           title='Europe'),
                      region[1])
778
    self.assertEqual(dict(codification='FR',
779 780 781
                           description='A Country',
                           int_index='1',
                           path='region/europe/france',
782
                           short_title='France',
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
                           title='France'),
                      region[2])
    # strings are encoded in UTF8
    self.assertTrue(isinstance(region[1]['title'], str))
    self.assertTrue(isinstance(region[1]['path'], str))
    for k in region[1].keys():
      self.assertTrue(isinstance(k, str), (k, type(k)))

  def test_Base_getCategoriesSpreadSheetMapping_DuplicateIdsAtSameLevel(self):
    # tests Base_getCategoriesSpreadSheetMapping when a document contain same
    # categories ID at the same level, in that case, a ValueError is raised
    import_file = makeFileUpload(
        'import_region_category_duplicate_ids_same_level.sxc')
    try:
      self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
             import_file=import_file)
    except ValueError, error:
      # 'france' is the duplicate ID in this spreadsheet
      self.assertTrue('france' in str(error), str(error))
    else:
      self.fail('ValueError not raised')
804

805 806 807 808 809 810 811 812 813 814 815
    # Base_getCategoriesSpreadSheetMapping performs checks on the spreadsheet,
    # an "invalid spreadsheet" error handler can be provided, to report errors
    # nicely.
    message_list = []
    def on_invalid_spreadsheet(message):
      message_list.append(message)

    import_file = makeFileUpload(
        'import_region_category_duplicate_ids_same_level.sxc')
    self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(import_file,
         invalid_spreadsheet_error_handler=on_invalid_spreadsheet)
816

817
    self.assertEqual(1, len(message_list))
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    self.assertTrue('france' in str(message_list[0]))

  def test_Base_getCategoriesSpreadSheetMapping_WrongHierarchy(self):
    # tests Base_getCategoriesSpreadSheetMapping when the spreadsheet has an
    # invalid hierarchy (#788)
    import_file = makeFileUpload(
        'import_region_category_wrong_hierarchy.sxc')
    try:
      self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
             import_file=import_file)
    except ValueError, error:
      # 'wrong_hierarchy' is the ID of the category where the problem happens
      self.assertTrue('wrong_hierarchy' in str(error), str(error))
    else:
      self.fail('ValueError not raised')

834 835 836 837 838 839 840 841 842 843 844 845 846
  def test_Base_getCategoriesSpreadSheetMapping_MultiplePaths(self):
    # If multiple paths is defined (for instance more than one * in paths
    # columns), then it should be an error and the error must be reported
    import_file = makeFileUpload(
        'import_region_category_multiple_paths.ods')
    try:
      self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
             import_file=import_file)
    except ValueError, error:
      self.assertTrue('More that one path is defined' in str(error), str(error))
    else:
      self.fail('ValueError not raised')

847 848 849 850 851 852 853
  def test_Base_getCategoriesSpreadSheetMapping_Id_is_reserved_property_name(self):
    # tests Base_getCategoriesSpreadSheetMapping reserved property name are only test for path column, not all.
    import_file = makeFileUpload(
        'import_region_category_with_reserved_id_in_title.sxc')
    mapping = self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
             import_file=import_file)
    self.assertTrue(isinstance(mapping, dict))
854
    self.assertEqual(['region'], list(mapping.keys()))
855 856
    region = mapping['region']
    self.assertTrue(isinstance(region, list))
857
    self.assertEqual(7, len(region))
858
    # Check that category can have a reserved property as title
859
    self.assertEqual(dict(codification='codification',
860 861 862 863 864
                           description='codification',
                           path='region/antartica',
                           short_title='codification',
                           title='codification'),
                      region[6])
865

866 867 868 869 870 871 872 873 874 875 876 877
    # Check that category cannot have a Base Category nor Category property
    # id/storage_id as their ID
    message_set = set()
    def on_invalid_spreadsheet(message):
      message_set.add(message.translate())
      # To continue processing and get all the errors
      return True

    self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
      import_file=makeFileUpload('import_category_with_reserved_id_in_id.sxc'),
      invalid_spreadsheet_error_handler=on_invalid_spreadsheet)

878 879
    self.assertEqual(message_set, {
           "The ID source_title in region at line 2 is invalid, "
880 881 882 883 884 885 886 887
           "it's a reserved property name",
           "The ID source_title in region at line 4 is invalid, "
           "it's a reserved property name",
           "The ID fallback_base_category_list in region at line 5 is invalid, "
           "it's a reserved property name",
           "The ID fallback_base_category_list in region at line 6 is invalid, "
           "it's a reserved property name",
           "The ID default_source_reference in region at line 7 is invalid, "
888
           "it's a reserved property name"})
889

890 891 892 893 894 895 896 897
  def test_BigSpreadSheet_can_be_parsed(self,):
    """Test than OOoimport can parse a file with more than 40000 lines
    """
    parser = OOoParser()
    parser.openFile(open(makeFilePath('import_big_spreadsheet.ods'), 'rb'))
    mapping = parser.getSpreadsheetsMapping()
    not_ok = 1
    for spread, values in mapping.iteritems():
898
      self.assertEqual(len(values), 41001)
899 900 901 902
      not_ok = 0
    if not_ok:
      self.fail('Spreadsheet not read!')

903
class TestOOoImportWeb(TestOOoImportMixin):
904 905 906 907 908 909 910 911 912 913 914 915 916
  def getTitle(self):
    """
      Return the title of the current test set.
    """
    return "ERP5 Site - OOo File importing (with web)"

  def getBusinessTemplateList(self):
    """
      Return the list of required business templates.
    """
    return ('erp5_base', 'erp5_web', 'erp5_ooo_import')

  def test_CategoryTool_importCategoryFileExpirationSupport(self):
917 918
    """Import category file with expiration request, and do it again to be
    sure that expired categories will not be expired again."""
919
    region = self.portal.portal_categories.region
Łukasz Nowak's avatar
Łukasz Nowak committed
920
    region.newContent(id='dummy_region')
921 922
    dummy_expired_region = region.newContent(id='dummy_expired_region')
    dummy_expired_region.expire()
923 924 925 926 927
    self.tic()
    self.portal.portal_categories.CategoryTool_importCategoryFile(
        import_file=makeFileUpload('import_region_category.sxc'),
        existing_category_list='expire')
    self.tic()
928
    self.assertEqual(4, len(region))
929 930
    self.assertTrue('dummy_region' in region.objectIds())
    self.assertEqual(region.dummy_region.getValidationState(), 'expired')
931 932
    self.assertTrue('dummy_expired_region' in region.objectIds())
    self.assertEqual(region.dummy_expired_region.getValidationState(), 'expired')
933 934 935 936
    self.assertTrue('europe' in region.objectIds())
    self.assertTrue('germany' in region.europe.objectIds())
    self.assertTrue('france' in region.europe.objectIds())
    france = region.europe.france
937
    self.assertEqual('France', france.getTitle())
938
    self.assertTrue(france.hasProperty('title'))
939 940 941
    self.assertEqual('A Country', france.getDescription())
    self.assertEqual('FR', france.getCodification())
    self.assertEqual(1, france.getIntIndex())
942

Jérome Perrin's avatar
Jérome Perrin committed
943 944 945
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestOOoImport))
946
  suite.addTest(unittest.makeSuite(TestOOoImportWeb))
Jérome Perrin's avatar
Jérome Perrin committed
947
  return suite