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


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

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 50 51 52 53 54 55 56 57 58 59

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
60
    file.__init__(self, path, 'rb')
61 62 63
    self.headers = {}

def makeFilePath(name):
64
  return os.path.join(os.path.dirname(__file__), 'test_document', name)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

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

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

  def getTitle(self):
    """
      Return the title of the current test set.
    """
    return "ERP5 Site - importing"

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

Jérome Perrin's avatar
Jérome Perrin committed
95
  def afterSetUp(self):
96 97 98 99
    """
      Initialize the ERP5 site.
    """
    self.login()
100 101 102 103

    # Enable oood on localhost:8008
    # This should probably become a test runner option
    self.pref = self.portal.portal_preferences.newContent(
104
                          portal_type='System Preference')
105 106 107 108 109 110 111 112 113 114 115 116 117
    self.pref.setPreferredOoodocServerAddress('localhost')
    self.pref.setPreferredOoodocServerPortNumber(8008)
    self.pref.enable()
    get_transaction().commit()
    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()])
    get_transaction().commit()
    self.tic()

118 119 120 121 122

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

Jérome Perrin's avatar
Jérome Perrin committed
123
  def login(self):
124 125 126 127 128 129 130 131 132 133 134 135
    """
      Create a new manager user and login.
    """
    user_name = 'bartek'
    user_folder = self.portal.acl_users
    user_folder._doAddUser(user_name, '', ['Manager', 'Owner', 'Assignor'], [])
    user = user_folder.getUserById(user_name).__of__(user_folder)
    newSecurityManager(None, user)

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

137 138 139 140
  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
141
    f = makeFileUpload('import_data_list.ods')
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    person_module = self.getPortal().person_module
    #purge existing persons
    person_module.manage_delObjects([id for id in person_module.getObjectIds()])
    get_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.ERP5Site_importObjectFromOOo(import_file=f, listbox=listbox)
Nicolas Delaby's avatar
Nicolas Delaby committed
157

158 159 160 161 162
  def stepCheckActivitiesCount(self, sequence=None, sequence_list=None, **kw):
    message_list = self.getPortal().portal_activities.getMessageList()
    self.assertEqual(1,len(message_list))
    method_id = message_list[0].method_id
    self.assertEqual('ERP5Site_importObjectFromOOoActivity',method_id)
Nicolas Delaby's avatar
Nicolas Delaby committed
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  def stepCheckImportedPersonList(self, sequence=None, sequence_list=None, **kw):
    person_module = self.getPortal().person_module
    for i in range(101):
      object = person_module['%s' % (i+1)]
      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())

  ##################################
  ##  Tests
  ##################################

  def test_01_ImportObjectFromOOoInActivities(self, quiet=QUIET, run=RUN_ALL_TEST):
    """
      Simulate import of OOo file true ERP5Site_importObjectFromOOoFastInput
      For Person Module.
    """
    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)

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  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',
                           title='Europe'),
                      region[1])
    self.assertEquals(dict(codification='FR',
                           description='A Country',
                           int_index='1',
                           path='region/europe/france',
                           title='France'),
                      region[2])
    # strings are encoded in UTF8
    self.assertTrue(isinstance(region[1]['title'], str))
Jérome Perrin's avatar
Jérome Perrin committed
217
    self.assertTrue(isinstance(region[1]['path'], str))
218 219
    for k in region[1].keys():
      self.assertTrue(isinstance(k, str), (k, type(k)))
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237

  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'))
    get_transaction().commit()
    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())

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
  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'))
    get_transaction().commit()
    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())
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  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'))
    get_transaction().commit()
    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())
    
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  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'))
    get_transaction().commit()
    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())
    
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  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'))
    get_transaction().commit()
    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()))

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  # simple OOoParser tests
  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'])
  
  def test_openFromString(self):
    parser = OOoParser()
    parser.openFromString(
        open(makeFilePath('import_data_list.ods'), 'rb').read())
    mapping = parser.getSpreadsheetsMapping()
    self.assertEquals(['Person'], mapping.keys())

328 329 330 331 332 333 334 335 336 337 338 339 340 341
  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'])

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  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

360

Jérome Perrin's avatar
Jérome Perrin committed
361 362 363 364
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestOOoImport))
  return suite