testOOoImport.py 38 KB
Newer Older
1
##############################################################################
2
# -*- coding: utf-8 -*-
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
import transaction
34 35 36 37 38
from zLOG import LOG
from Testing import ZopeTestCase
from AccessControl.SecurityManagement import newSecurityManager
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.Sequence import SequenceList
39
from Products.ERP5OOo.OOoUtils import OOoParser
40 41 42 43 44 45 46 47 48 49
from Products.ERP5.Document.Document import ConversionError
from DateTime import DateTime
import transaction

person_current_id = 1

def shout(msg):
  msg = str(msg)
  ZopeTestCase._print('\n ' + msg)
  LOG('Testing... ', 0, msg)
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

def unpackData(data):
  """
  Unpack Pdata into string
  """
  if isinstance(data, str):
    return data
  else:
    data_list = []
    while data is not None:
      data_list.append(data.data)
      data = data.next
    return ''.join(data_list)

class FileUploadTest(file):

  __allow_access_to_unprotected_subobjects__=1

  def __init__(self, path, name):
    self.filename = name
70
    file.__init__(self, path, 'rb')
71 72 73
    self.headers = {}

def makeFilePath(name):
74
  return os.path.join(os.path.dirname(__file__), 'test_document', name)
75 76 77 78 79 80 81 82 83 84 85 86 87

def makeFileUpload(name):
  path = makeFilePath(name)
  return FileUploadTest(path, name)

class TestOOoImport(ERP5TypeTestCase):
  """
    ERP5  test import object list from OOo Document
  """

  # pseudo constants
  RUN_ALL_TEST = 1
  QUIET = 0
88 89
  gender_base_cat_id    = 'gender'
  function_base_cat_id  = 'function'
90 91 92 93 94 95 96 97 98

  ##################################
  ##  ZopeTestCase Skeleton
  ##################################

  def getTitle(self):
    """
      Return the title of the current test set.
    """
99
    return "ERP5 Site - OOo File importing"
100 101 102 103 104

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

Jérome Perrin's avatar
Jérome Perrin committed
107
  def afterSetUp(self):
108 109 110 111
    """
      Initialize the ERP5 site.
    """
    self.login()
112 113 114 115

    # Enable oood on localhost:8008
    # This should probably become a test runner option
    self.pref = self.portal.portal_preferences.newContent(
116
                          portal_type='Preference')
117 118 119
    self.pref.setPreferredOoodocServerAddress('localhost')
    self.pref.setPreferredOoodocServerPortNumber(8008)
    self.pref.enable()
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

    # create browser_id_manager
    ZopeTestCase.installProduct('Sessions')
    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')

    transaction.commit()
147 148 149 150 151 152
    self.tic()

  def beforeTearDown(self):
    region = self.portal.portal_categories.region
    region.manage_delObjects(list(region.objectIds()))
    self.portal.portal_preferences.manage_delObjects([self.pref.getId()])
153 154 155 156 157 158
    gender = self.portal.portal_categories.gender
    function  = self.portal.portal_categories.function
    gender.manage_delObjects(list(gender.objectIds()))
    function.manage_delObjects(list(function.objectIds()))

    transaction.commit()
159 160
    self.tic()

161 162 163 164 165

  ##################################
  ##  Useful methods
  ##################################

Jérome Perrin's avatar
Jérome Perrin committed
166
  def login(self):
167 168 169 170 171
    """
      Create a new manager user and login.
    """
    user_name = 'bartek'
    user_folder = self.portal.acl_users
172 173
    user_folder._doAddUser(user_name, '', ['Manager', 'Owner', 'Assignor',
                               	           'Associate', 'Auditor', 'Author'], [])
174 175 176 177 178 179
    user = user_folder.getUserById(user_name).__of__(user_folder)
    newSecurityManager(None, user)

  ##################################
  ##  Basic steps
  ##################################
Nicolas Delaby's avatar
Nicolas Delaby committed
180

181 182 183 184
  def stepTic(self, sequence=None, sequence_list=None, **kw):
    self.tic()

  def stepImportRawDataFile(self, sequence=None, sequence_list=None, **kw):
Nicolas Delaby's avatar
Nicolas Delaby committed
185
    f = makeFileUpload('import_data_list.ods')
186 187 188
    person_module = self.getPortal().person_module
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
189
    transaction.commit(); self.tic()
190 191 192 193 194 195 196 197 198 199
    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'}
    )
200
    person_module.Base_importFile(import_file=f, listbox=listbox)
Nicolas Delaby's avatar
Nicolas Delaby committed
201

202
  def stepCheckActivitiesCount(self, sequence=None, sequence_list=None, **kw):
203 204 205 206 207
    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
208

209
  def stepCheckImportedPersonList(self, sequence=None, sequence_list=None, **kw):
210
    global person_current_id
211 212
    person_module = self.getPortal().person_module
    for i in range(101):
213 214
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
215 216 217 218
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('Doe %s' % (i), object.getLastName())
      self.assertEqual('john.doe%s@foo.com' % (i), object.getDefaultEmailText())
219
    person_current_id =  person_current_id+101
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 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 387 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
  def stepCheckImportedPersonListBlank(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(101):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('Doe %s' % (i), object.getLastName())
      self.assertEqual('john.doe%s@foo.com' % (i), object.getDefaultEmailText())
    person_current_id = person_current_id+101

  def stepCheckImportedPersonListCategory(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(10):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('male', object.getGender())
      self.assertEqual('director', object.getFunction())
    person_current_id = person_current_id+10

  def stepCheckAuthorImportedPersonList(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(10):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('male', object.getGender())
      self.assertEqual('director', object.getFunction())
    person_current_id=person_current_id+10

  def stepCheckImportedPersonListFreeText(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(10):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('male', object.getGenderFreeText())
      self.assertEqual('Director', object.getFunctionFreeText())
    person_current_id=person_current_id+10

  def stepCheckImportedPersonListAccentuated(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(10):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      title = 'John Doe é %s' % (i)
      #encode_title = title.encode('UTF-8')
      self.assertEqual(title, object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('male', object.getGender())
      self.assertEqual('director', object.getFunction())
    person_current_id = person_current_id+10

  def stepCheckXLSImportedPersonList(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(10):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('Doe %s' % (i), object.getLastName())
      self.assertEqual('john.doe%s@foo.com' % (i), object.getDefaultEmailText())
    person_current_id = person_current_id+10

  def stepCheckImportedPersonListWithDates(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(9):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('male', object.getGender())
      self.assertEqual(DateTime('2008/02/0%s %s' % (i+1, 'GMT')), object.getStartDate())
    object = person_module['%s' % (object_id+1)]
    self.assertEqual(DateTime('2008/02/%s %s' % (10, 'GMT')), object.getStartDate())
    person_current_id = person_current_id+10

  def stepCheckImportFloatsAndPercentage(self, sequence=None, sequence_list=None, **kw):
    currency_module = self.getPortal().currency_module
    for i in range(10):
      height_quantity = 1000.3 + i
      object = currency_module['%s' % (i + 1)]
      self.assertEqual('Currency %s' % (i), object.getTitle())
      self.assertEqual(height_quantity, object.getHeightQuantity())

  def stepCheckImportedPersonList_1(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(1000):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('Doe %s' % (i), object.getLastName())
      self.assertEqual('john.doe%s@foo.com' % (i), object.getDefaultEmailText())
    person_current_id =  person_current_id+1000

  def stepCheckImportedPersonList_2(self, sequence=None, sequence_list=None, **kw):
    global person_current_id
    person_module = self.getPortal().person_module
    for i in range(10000):
      object_id = i + person_current_id
      object = person_module['%s' % (object_id)]
      self.assertEqual('John Doe %s' % (i), object.getTitle())
      self.assertEqual('John', object.getFirstName())
      self.assertEqual('Doe %s' % (i), object.getLastName())
      self.assertEqual('john.doe%s@foo.com' % (i), object.getDefaultEmailText())
    person_current_id =  person_current_id+10000

  def stepCheckImportedOrganisationList(self, sequence=None, sequence_list=None, **kw):
    organisation_module = self.getPortal().organisation_module
    for i in range(10):
      object_id = i + 1
      object = organisation_module['%s' % (object_id)]
      self.assertEqual('Foo Organisation %s' % (i), object.getTitle())
      self.assertEqual('Description organisation %s' % (i), object.getDescription())
      self.assert_('1234567%s' % (i) in object.getTelephoneText())
      self.assertEqual('org%s@foo.com' % (i), object.getEmailText())

  def stepImportFileNoMapping(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_list.ods')
    #self.logMessage("f : %s" % str(f))

    person_module = self.getPortal().person_module
    person_module.Base_importFile(import_file=f, listbox=())
    self.assertRaises(ConversionError, person_module.Base_importFile, import_file=f, listbox=())
    #self.logMessage("Validation failed : %s" % kw)

  def stepImportFileWithBlankLine(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_list_blank_line.ods')
    person_module = self.getPortal().person_module
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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')
    person_module = self.getPortal().person_module
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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 stepImportFileWithDates(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_with_dates.ods')
    person_module = self.getPortal().person_module
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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)
413

414
  def stepImportFloatsAndPercentage(self, sequence=None, sequence_list=None, **kw):
415
    """
416 417
      This test make sure that either floats (1000,9), sientific numbers (1,00E+003)
      or percentage (19%) are correctly imported .
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 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 505 506 507 508 509 510 511 512 513 514 515 516 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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    f = makeFileUpload('import_float_and_percentage.ods')
    currency_module = self.getPortal().currency_module
    currency_module.manage_delObjects([id for id in currency_module.getObjectIds()])
    transaction.commit(); self.tic()
    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
    #purge existing persons
    organisation_module.manage_delObjects([id for id in organisation_module.getObjectIds()])
    transaction.commit(); self.tic()
    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):
    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
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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 stepImportFileWithFreeText(self, sequence=None, sequence_list=None, **kw):
    f = makeFileUpload('import_data_with_categories.ods')
    person_module = self.getPortal().person_module
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    transaction.commit(); self.tic()
    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
  ##################################
  def test_01_ImportFileLine(self, quiet=QUIET, run=RUN_ALL_TEST):
    # Simulate import of OOo file Base_importFile for Person Module.
567 568 569 570 571 572 573 574 575 576 577
    if not run: return
    sequence_list = SequenceList()
    step_list = [ 'stepImportRawDataFile'
                 ,'stepCheckActivitiesCount'
                 ,'Tic'
                 ,'stepCheckImportedPersonList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
  def test_02_ImportFileBlankLine(self, quiet=QUIET, run=RUN_ALL_TEST):
    #Simulate import of an OOo file with blank lines.
    #self.logMessage('Simulate import of an OOo file with blank lines')
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithBlankLine'
                  ,'Tic'
                  ,'stepCheckImportedPersonListBlank'
                 ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_03_ImportNoMapping(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [ 'stepImportFileNoMapping'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_04_ImportFileWithCategory(self, quiet=QUIET, run=RUN_ALL_TEST):
    #self.logMessage('Simulate import of an OOo file with blank lines')
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithCategory'
                  ,'Tic'
                  ,'stepCheckImportedPersonListCategory'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_05_ImportOrganisation(self, quiet=QUIET, run=RUN_ALL_TEST):
   #self.logMessage('Simulate import of an OOo file with blank lines')
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportOrganisation'
                  ,'Tic'
                  ,'stepCheckImportedOrganisationList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_06_AuthorImportFile(self, quiet=QUIET, run=RUN_ALL_TEST):
    #self.logMessage('Simulate import of an OOo file with blank lines')
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepAuthorImportFile'
                  ,'Tic'
                  ,'stepCheckAuthorImportedPersonList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_07_ImportFileWithFreeText(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithFreeText'
                  ,'Tic'
                  ,'stepCheckImportedPersonListFreeText'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_08_ImportFileWithAccentuatedText(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportFileWithAccentuatedText'
                  ,'Tic'
                  ,'stepCheckImportedPersonListAccentuated'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_09_ImportXLSFile(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [ 'stepImportXLSFile'
                 ,'Tic'
                 ,'stepCheckXLSImportedPersonList'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_10_ImportFileWithDates(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [ 'stepImportFileWithDates'
                 ,'Tic'
                 ,'stepCheckImportedPersonListWithDates'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_11_ImportFloatAndPercentage(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [ 'stepImportFloatsAndPercentage'
                 ,'Tic'
                 ,'stepCheckImportFloatsAndPercentage'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  def test_12_ImportBigFile_1(self, quiet=QUIET, run=RUN_ALL_TEST):
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportBigFile_1'
                  ,'Tic'
                  ,'stepCheckImportedPersonList_1'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)

  '''
  def test_12_ImportBigFile_2(self, quiet=QUIET, run=RUN_ALL_TEST):
    #self.logMessage('Simulate import of an OOo file with blank lines')
    if not run: return
    sequence_list = SequenceList()
    step_list = [  'stepImportBigFile_2'
                  ,'Tic'
                  ,'stepCheckImportedPersonList_2'
                ]
    sequence_string = ' '.join(step_list)
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)
  '''
715

716
  # CategoryTool_importCategoryFile tests
717 718 719 720
  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'))
721
    transaction.commit()
722 723 724 725 726 727 728 729
    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
    self.assertEquals('France', france.getTitle())
730
    self.assertTrue(france.hasProperty('title'))
731 732 733 734
    self.assertEquals('A Country', france.getDescription())
    self.assertEquals('FR', france.getCodification())
    self.assertEquals(1, france.getIntIndex())

735 736 737 738
  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'))
739
    transaction.commit()
740 741 742 743 744 745 746 747 748 749 750
    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
    self.assertEquals('France', france.getTitle())
    self.assertEquals('A Country', france.getDescription())
    self.assertEquals('FR', france.getCodification())
    self.assertEquals(1, france.getIntIndex())
751 752 753 754 755
  
  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'))
756
    transaction.commit()
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    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
    self.assertEquals('France', france.getTitle())
    self.assertEquals('A Country', france.getDescription())
    self.assertEquals('FR', france.getCodification())
    self.assertEquals(1, france.getIntIndex())
    
  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'))
775
    transaction.commit()
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    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
    self.assertEquals('Frànce', france.getTitle())
    self.assertEquals('A Country', france.getDescription())
    self.assertEquals('FR', france.getCodification())
    self.assertEquals(1, france.getIntIndex())

  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'))
794
    transaction.commit()
795 796 797 798 799 800 801 802
    self.tic()
    region = self.portal.portal_categories.region
    self.assertEqual(1, len(region))
    self.assertEquals(['europe'], list(region.objectIds()))
    self.assertEquals(['france'], list(region.europe.objectIds()))
    self.assertEquals(['europe'], list(region.europe.france.objectIds()))
    self.assertEquals(['france'], list(region.europe.france.europe.objectIds()))
    self.assertEquals([], list(region.europe.france.europe.france.objectIds()))
803

804 805

  # OOoParser tests
806 807 808 809 810 811 812 813 814 815 816 817
  def test_getSpreadSheetMapping(self):
    parser = OOoParser()
    parser.openFile(open(makeFilePath('import_data_list.ods'), 'rb'))
    mapping = parser.getSpreadsheetsMapping()
    self.assertEquals(['Person'], mapping.keys())
    person_mapping = mapping['Person']
    self.assertTrue(isinstance(person_mapping, list))
    self.assertTrue(102, len(person_mapping))
    self.assertEquals(person_mapping[0],
       ['Title', 'First Name', 'Last Name', 'Default Email Text'])
    self.assertEquals(person_mapping[1],
       ['John Doe 0', 'John', 'Doe 0', 'john.doe0@foo.com'])
818

819 820 821 822 823 824 825
  def test_openFromString(self):
    parser = OOoParser()
    parser.openFromString(
        open(makeFilePath('import_data_list.ods'), 'rb').read())
    mapping = parser.getSpreadsheetsMapping()
    self.assertEquals(['Person'], mapping.keys())

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
  def test_getSpreadSheetMappingStyle(self):
    parser = OOoParser()
    parser.openFile(open(makeFilePath('import_data_list_with_style.ods'), 'rb'))
    mapping = parser.getSpreadsheetsMapping()
    self.assertEquals(['Feuille1'], mapping.keys())
    self.assertEquals(mapping['Feuille1'][1],
                      ['a line with style'])
    self.assertEquals(mapping['Feuille1'][2],
                      ['a line with multiple styles'])
    self.assertEquals(mapping['Feuille1'][3],
                      ['http://www.erp5.org'])
    self.assertEquals(mapping['Feuille1'][4],
                      ['john.doe@example.com'])

  def test_getSpreadSheetMappingDataTypes(self):
    parser = OOoParser()
    parser.openFile(open(makeFilePath('import_data_list_data_type.ods'), 'rb'))
    mapping = parser.getSpreadsheetsMapping()
    self.assertEquals(['Feuille1'], mapping.keys())
    self.assertEquals(mapping['Feuille1'][0],
                      ['1234.5678'])
    self.assertEquals(mapping['Feuille1'][1],
                      ['1234.5678'])
    self.assertEquals(mapping['Feuille1'][2],
                      ['0.1'])
    self.assertEquals(mapping['Feuille1'][3],
                      ['2008-11-14'])
    self.assertEquals(mapping['Feuille1'][4],
                      ['2008-11-14T10:20:30']) # supported by DateTime
    self.assertEquals(mapping['Feuille1'][5],
                      ['PT12H34M56S']) # maybe not good, this is raw format

  # 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))
    self.assertEquals(['region'], list(mapping.keys()))
    region = mapping['region']
    self.assertTrue(isinstance(region, list))
    self.assertEquals(6, len(region))
    # base category is contained in the list
    self.assertEquals(dict(path='region',
                           title='region'),
                      region[0])
    self.assertEquals(dict(path='region/europe',
873
                           short_title='Europe',
874 875 876 877 878 879
                           title='Europe'),
                      region[1])
    self.assertEquals(dict(codification='FR',
                           description='A Country',
                           int_index='1',
                           path='region/europe/france',
880
                           short_title='France',
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
                           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')
    
    # 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)
    
    self.assertEquals(1, len(message_list))
    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')


Jérome Perrin's avatar
Jérome Perrin committed
933 934 935 936
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestOOoImport))
  return suite