Beispiel #1
0
 def test_01_CheckClassTool(self):
     """
   Make sure that portal_classes exists
 """
     portal = self.portal
     self.assertNotEqual(None, getattr(portal, "portal_classes", None))
     get_transaction().commit()
def publish_object_created(ob, event):
    parent = aq_parent(ob)
    topic = "/".join(ob.getPhysicalPath())
    if parent is not None:
        message = {
            "guards": get_allowed_roles_and_users_guard(ob),
            "payload": {
                "created": [{
                    "@id": ob.absolute_url(),
                    "parent": {
                        "@id": parent.absolute_url()
                    }
                }]
            },
        }
    else:
        message = {
            "guards": get_allowed_roles_and_users_guard(ob),
            "payload": {
                "created": [{
                    "@id": ob.absolute_url()
                }]
            },
        }
    dm = CallbackDataManager(publish_message, encode_message(message), topic)
    get_transaction().join(dm)
Beispiel #3
0
  def test_30_resolveCategory(self):
    portal = self.getPortal()
    category_tool = portal.portal_categories
    module = portal.sale_order_module
    order = module.newContent(id='foo', portal_type='Sale Order')
    self.assertNotEquals(order, None)
    line = order.newContent(id='bar', portal_type='Sale Order Line')
    self.assertNotEquals(line, None)
    cell = line.newContent(id='baz', portal_type='Sale Order Cell')
    self.assertNotEquals(cell, None)
    get_transaction().commit()
    self.tic()

    for relative_url, value in (
            ('sale_order_module', module),
            ('sale_order_module/foo', order),
            ('sale_order_module/bar', None),
            ('sale_order_module/order', None),
            ('sale_order_module/sale_order_module', None),
            ('sale_order_module/foo/bar', line),
            ('sale_order_module/foo/foo', None),
            ('sale_order_module/foo/order', None),
            ('sale_order_module/foo/sale_order_module', None),
            ('sale_order_module/foo/bar/baz', cell),
            ('sale_order_module/foo/bar/bar', None),
            ('sale_order_module/foo/bar/foo', None),
            ('sale_order_module/foo/bar/order', None),
            ('sale_order_module/foo/bar/sale_order_module', None),
            ):
      obj = category_tool.resolveCategory(relative_url)
      self.assertEquals(obj, value)
      obj = category_tool.resolveCategory('order/' + relative_url)
      self.assertEquals(obj, value)
      obj = category_tool.resolveCategory('mapping/order/' + relative_url)
      self.assertEquals(obj, value)
Beispiel #4
0
 def test_31_assert_raise_if_base_category_is_missing(self):
   #First remove Base Category
   self.portal.portal_categories.manage_delObjects(['region'])
   obj = self.portal.person_module.newContent(portal_type='Person')
   get_transaction().commit()
   try:
     #Setters
     self.assertRaises(AttributeError, getattr, obj, 'setRegion')
     self.assertRaises(AttributeError, getattr, obj, 'setRegionValueList')
     self.assertRaises(AttributeError, getattr, obj, 'setRegionList')
     #getters
     self.assertRaises(AttributeError, getattr, obj, 'getRegion')
     self.assertRaises(AttributeError, getattr, obj, 'getRegionValueList')
     self.assertRaises(AttributeError, getattr, obj, 'getRegionList')
     # Tester are always present, because they are genereted on the BaseClass
     # during startup
     # self.assertRaises(AttributeError, getattr, obj, 'hasRegion')
   finally:
     #add Base Category
     self.portal.portal_categories.newContent(id='region', portal_type='Base Category')
   get_transaction().commit()
   #check Method exists after base_category creation
   #Setters
   self.assertTrue(getattr(obj, 'setRegion') is not None)
   self.assertTrue(getattr(obj, 'setRegionValueList') is not None)
   self.assertTrue(getattr(obj, 'setRegionList') is not None)
   #getters
   self.assertTrue(getattr(obj, 'getRegion') is not None)
   self.assertTrue(getattr(obj, 'getRegionValueList') is not None)
   self.assertTrue(getattr(obj, 'getRegionList') is not None)
Beispiel #5
0
 def test_29_renameBaseCategory(self):
   bc = self.portal.portal_categories.newContent(
                         portal_type='Base Category',
                         id='first_id')
   get_transaction().commit()
   self.tic()
   bc.setId('new_id')
   self.assertEquals('new_id', bc.getId())
Beispiel #6
0
 def beforeTearDown(self):
   self._ignore_log_errors()
   if self.portal_activities_backup is not None:
     self.portal._setObject('portal_activities',
                            self.portal_activities_backup)
     get_transaction().commit()
     del self.portal_activities_backup
   return super(TestXMLMatrix, self).beforeTearDown()
 def add(self,
         url=None,
         method='GET',
         params=None,
         headers=None,
         payload=_marker):
     task_id, task = make_task(url, method, params, headers, payload)
     get_transaction().join(self.transaction_data_manager(self, task))
     return task_id
Beispiel #8
0
 def test_DocumentationHelperActivities(self):
     """
 Using documentation helpers should not create any activity
 """
     portal = self.getPortal()
     folder = portal.newContent(portal_type="Folder", id="test_folder")
     get_transaction().commit()
     self.tic()
     doc_helper = folder.asDocumentationHelper()
     get_transaction().commit()
     self.assertEquals(0, len(portal.portal_activities.getMessageList()))
def publish_object_commented(ob, event):
    topic = "/".join(ob.getPhysicalPath())
    parent = aq_parent(ob)
    comment = event.comment
    author = comment.author_username

    if author:
        portal_membership = getToolByName(ob, "portal_membership")
        member = portal_membership.getMemberById(author)
        if member is not None:
            author = member.getProperty("fullname") or author
    else:
        author = comment.author_name

    guards_object = get_allowed_roles_and_users_guard(ob)
    guards_comment = get_allowed_roles_and_users_guard(comment)
    if ("Anonymous" in guards_comment["allowedRolesAndUsers"]["tokens"]
            and "Anonymous"
            not in guards_object["allowedRolesAndUsers"]["tokens"]):
        guards = guards_object
    else:
        guards = guards_comment

    if parent is not None:
        message = {
            "guards": guards,
            "payload": {
                "commented": [{
                    "@id": ob.absolute_url(),
                    "parent": {
                        "@id": parent.absolute_url()
                    },
                    "title": ob.title,
                    "text": comment.text,
                    "author": author,
                }]
            },
        }
    else:
        message = {
            "guards": guards,
            "payload": {
                "commented": [{
                    "@id": ob.absolute_url(),
                    "title": ob.title,
                    "text": comment.text,
                    "author": author,
                }]
            },
        }
    dm = CallbackDataManager(publish_message, encode_message(message), topic)
    get_transaction().join(dm)
Beispiel #10
0
 def _changeCachePlugin(self, portal_type, storage_duration = 86400):
   """ Change current cache plugin with new one. """
   portal_caches = self.portal.portal_caches
   session_cache_factory = getattr(portal_caches, SESSION_CACHE_FACTORY)
   # remove current cache plugin
   session_cache_factory.manage_delObjects(list(session_cache_factory.objectIds()))
   cache_plugin = session_cache_factory.newContent(portal_type=portal_type)
   cache_plugin.setCacheDuration(storage_duration)
   cache_plugin.setIntIndex(0)
   if portal_type == 'Distributed Ram Cache':
     cache_plugin.edit(specialise='portal_memcached/default_memcached_plugin')
   get_transaction().commit()    
   portal_caches.updateCache()
Beispiel #11
0
 def test_17_CategoriesAndDomainSelection(self):
   """ Tests Categories and Domain Selection """
   category_tool = self.getCategoryTool()
   base = category_tool.newContent(portal_type='Base Category',
                                  id='test_base_cat')
   test = base.newContent(portal_type='Category', id='test_cat')
   base.recursiveReindexObject()
   obj = self.getOrganisationModule().newContent(
         portal_type = 'Organisation')
   obj.setCategoryList(['test_base_cat/test_cat'])
   get_transaction().commit()
   self.tic()
   self.assert_(obj in [x.getObject() for x in test.getCategoryMemberValueList()])
Beispiel #12
0
 def perform_job(self, job):
     self.procline(
         'Initializing pyramid for %s from %s' % (
             job.func_name, job.origin
         )
     )
     try:
         super(PyramidWorker, self).perform_job(job)
     except:
         if HAVE_TRANSACTION:
             get_transaction().abort()
         raise
     else:
         if HAVE_TRANSACTION:
             get_transaction().commit()
     finally:
         self.environment['closer']()
Beispiel #13
0
  def test_add_dimension(self):
    matrix = self.matrix

    cell_range = [['1', ]]
    kwd = {'base_id' : 'quantity'}
    matrix.setCellRange(*cell_range, **kwd)

    cell = matrix.newCell(*['1',], **kwd)
    get_transaction().commit()
    self.tic()
    
    cell_range = [['1', ], ['a', ]]
    matrix.setCellRange(*cell_range, **kwd)
    self.assertEquals(0, len(matrix.getCellValueList(**kwd)))
    new_cell = matrix.newCell(*['1', 'a'], **kwd)
    get_transaction().commit()
    self.tic()
Beispiel #14
0
  def test_del_dimension(self):
    matrix = self.matrix

    cell_range = [['1', ], ['a', ]]
    kwd = {'base_id' : 'quantity'}
    matrix.setCellRange(*cell_range, **kwd)

    for place in cartesianProduct(cell_range):
      matrix.newCell(*place, **kwd)
    get_transaction().commit()
    self.tic()
    
    cell_range = [['1', ]]
    matrix.setCellRange(*cell_range, **kwd)
    self.assertEquals(0, len(matrix.getCellValueList(**kwd)))
    get_transaction().commit()
    self.tic()
Beispiel #15
0
  def test_12_GetRelatedValueAndValueList(self):
    # Test if an infinite loop of the acquisition for a single value is working
    # Typical error results from bad brain (do not copy, use aliases for zsqlbrain.py)
    p1 = self.getPersonModule()._getOb(self.id1)
    p2 = self.getPersonModule()._getOb(self.id2)
    o1 = self.getOrganisationModule()._getOb(self.id1)
    p1.setGenderValue(o1)
    get_transaction().commit()
    self.tic() # This is required

    self.assertEqual(p1.getGenderValue(),o1)
    self.assertEqual(o1.getGenderRelatedValueList(),[p1])
    p2.setGenderValue(o1) # reindex implicit
    get_transaction().commit()
    self.tic()

    self.assertEqual(len(o1.getGenderRelatedValueList()),2)
Beispiel #16
0
    def test_02_CheckFileWriteIsTransactional(self):
        portal = self.portal
        portal_classes = portal.portal_classes

        self.assertEqual(
            portal_classes.getLocalDocumentList(),
            [],
            "Test environment is dirty. Please clean up the instance home of "
            "the test environment and fix up tests that might have left over "
            "files at %s" % getConfiguration().instancehome,
        )
        portal_classes.newDocument("Toto")
        get_transaction().abort()
        self.assertNotEqual(portal_classes.getLocalDocumentList(), ["Toto"])

        portal_classes.newDocument("Toto")
        get_transaction().commit()
        self.assertEqual(portal_classes.getLocalDocumentList(), ["Toto"])
def publish_object_moved(ob, event):
    topic = "/".join(ob.getPhysicalPath())
    if event.oldParent is not None and event.newParent is not None:
        new_id = ob.absolute_url()
        old_id = new_id.replace(
            event.newParent.absolute_url() + "/" + event.newName,
            event.oldParent.absolute_url() + "/" + event.oldName,
        )
        parent = aq_parent(ob)
        parent_new_id = parent.absolute_url()
        parent_old_id = parent_new_id.replace(
            event.newParent.absolute_url() + "/" + event.newName,
            event.oldParent.absolute_url() + "/" + event.oldName,
        )
        message = {
            "guards":
            get_allowed_roles_and_users_guard(ob.__of__(event.oldParent)),
            "payload": {
                "removed": [{
                    "@id": old_id,
                    "parent": {
                        "@id": parent_old_id
                    }
                }]
            },
        }
        dm = CallbackDataManager(publish_message, encode_message(message),
                                 topic)
        get_transaction().join(dm)

        message = {
            "guards": get_allowed_roles_and_users_guard(ob),
            "payload": {
                "created": [{
                    "@id": new_id,
                    "parent": {
                        "@id": parent_new_id
                    }
                }]
            },
        }
        dm = CallbackDataManager(publish_message, encode_message(message),
                                 topic)
        get_transaction().join(dm)
Beispiel #18
0
 def mycommit(self, ip=None):
     if not ip:
         ipname = "all"
     else:
         ipname = ip.id
     self.log.info('commiting group of ips ending with %s' % ipname)
     trans = get_transaction()
     trans.note('FixIps reconnect ips')
     trans.commit()
     self.ccount = 0
    def __call__(self):
        obj = self.event.object
        interpolator = IStringInterpolator(obj)
        payload = interpolate(json.loads(self.element.payload), interpolator)
        topic = "/".join(obj.getPhysicalPath())

        guards_context = get_allowed_roles_and_users_guard(self.context)
        guards_event = get_allowed_roles_and_users_guard(obj)
        if ("Anonymous" in guards_event["allowedRolesAndUsers"]["tokens"]
                and "Anonymous"
                not in guards_context["allowedRolesAndUsers"]["tokens"]):
            guards = guards_context
        else:
            guards = guards_event

        message = {"guards": guards, "payload": {"notifications": [payload]}}
        dm = CallbackDataManager(publish_message, encode_message(message),
                                 topic)
        get_transaction().join(dm)
 def rebuild(self):
     ccount = 0
     for tomany in getSubObjectsMemo(self.dmd, self.filter, self.decend):
         self.log.debug("rebuilding keys for relation %s on object %s" %
                             (tomany.getId(), aq_parent(tomany).getId()))
         ccount += tomany.rebuildKeys(self.log)
         if ccount >= self.options.commitCount and not self.options.noCommit:
             trans = get_transaction()
             trans.note('ToManyRebuildKeys rebuilt keys')
             trans.commit()
             ccount = 0
             self.dmd._p_jar.sync()
             gc.collect()
     if self.options.noCommit:
         self.log.info("not commiting any changes")
     else:
         trans = get_transaction()
         trans.note('ToManyRebuildKeys rebuilt keys')
         trans.commit()
Beispiel #21
0
 def mycommit(self, ip=None):
     if not ip:
         ipname = "all"
     else:
         ipname = ip.id
     self.log.info('commiting group of ips ending with %s' % ipname)
     trans = get_transaction()
     trans.note('FixIps reconnect ips')
     trans.commit()
     self.ccount = 0
Beispiel #22
0
  def test_13_RenameCategory(self):
    france = self.portal.portal_categories.resolveCategory(
                                            'region/europe/west/france')
    self.assertNotEqual(france, None)

    p1 = self.getPersonModule()._getOb(self.id1)
    p1.setRegion('europe/west/france')
    get_transaction().commit()
    self.tic()

    west = self.portal.portal_categories.resolveCategory('region/europe/west')
    west.setId("ouest")
    get_transaction().commit()
    self.tic()

    self.assertEqual(west,
      self.portal.portal_categories.resolveCategory('region/europe/ouest'))
    self.assertEqual(p1.getRegion(), 'europe/ouest/france')
    self.failUnless(p1 in west.getRegionRelatedValueList())
 def rebuild(self):
     ccount = 0
     for tomany in getSubObjectsMemo(self.dmd, self.filter, self.decend):
         self.log.debug("rebuilding keys for relation %s on object %s" %
                        (tomany.getId(), aq_parent(tomany).getId()))
         ccount += tomany.rebuildKeys(self.log)
         if ccount >= self.options.commitCount and not self.options.noCommit:
             trans = get_transaction()
             trans.note('ToManyRebuildKeys rebuilt keys')
             trans.commit()
             ccount = 0
             self.dmd._p_jar.sync()
             gc.collect()
     if self.options.noCommit:
         self.log.info("not commiting any changes")
     else:
         trans = get_transaction()
         trans.note('ToManyRebuildKeys rebuilt keys')
         trans.commit()
Beispiel #24
0
  def test_13b_RenameCategoryUsingCutAndPaste(self):
    france = self.portal.portal_categories.resolveCategory(
                                            'region/europe/west/france')
    self.assertNotEqual(france, None)

    p1 = self.getPersonModule()._getOb(self.id1)
    p1.setRegion('europe/west/france')
    get_transaction().commit()
    self.tic()

    europe = self.portal.portal_categories.resolveCategory('region/europe')
    west = europe.west
    cb_data = europe.manage_cutObjects(['west'])
    self.portal.portal_categories.region.manage_pasteObjects(cb_data)
    get_transaction().commit()
    self.tic()

    self.assertEqual(west,
      self.portal.portal_categories.resolveCategory('region/west'))
    self.assertEqual(p1.getRegion(), 'west/france')
    self.failUnless(p1 in west.getRegionRelatedValueList())
Beispiel #25
0
    def test_02_Expiration(self):
      """Check if a transaction variable does not persist over multiple
      transactions.
      """
      tv = getTransactionalVariable()
      self.failIfEqual(tv, None)

      tv.clear()
      self.failUnlessEqual(len(tv), 0)

      # Commit and check.
      tv['toto'] = 'titi'
      self.failUnlessEqual(tv['toto'], 'titi')
      get_transaction().commit()
      self.failIf('toto' in tv)

      # Abort and check.
      tv['toto'] = 'titi'
      self.failUnlessEqual(tv['toto'], 'titi')
      get_transaction().abort()
      self.failIf('toto' in tv)
Beispiel #26
0
  def test_change_dimension_cell_change_id(self):
    # The dimension change, a cell is kept, but receives a new ID because its
    # coordinate changes
    matrix = self.matrix

    cell_range = [['1', '2',], ['a', 'b',]]
    kwd = {'base_id' : 'quantity'}
    matrix.setCellRange(*cell_range, **kwd)

    for place in cartesianProduct(cell_range):
      matrix.newCell(*place, **kwd)
    
    cell = matrix.getCell('2', 'b', **kwd)
    self.assertEquals('quantity_1_1', cell.getId())
    cell.setTitle('This one')
    get_transaction().commit()
    self.tic()
    
    cell_range = [['2', '3', ], ['b', 'c',]]
    matrix.setCellRange(*cell_range, **kwd)
    get_transaction().commit()
    self.assertFalse('quantity_0_1' in matrix.objectIds())

    cell = matrix.getCell('2', 'b', **kwd)
    # this is the same cell, but it just changed id
    self.assertEquals('quantity_0_0', cell.getId())
    self.assertEquals('This one', cell.getTitle())
  
    get_transaction().commit()
    self.tic()

    # the cell is still in catalog
    self.assertEquals(cell,
        self.portal.portal_catalog.getObject(cell.getUid()))
Beispiel #27
0
  def test_16_GetRelatedValues(self):
    """ Checks on getting related values"""
    pc = self.getCategoriesTool()
    bc = pc.newContent(portal_type='Base Category', id='related_value_test')
    self.failUnless(bc is not None)
    get_transaction().commit()
    self.tic()
    # A newly created base category should be referred to only by itself
    value_list = pc.getRelatedValueList(bc)
    self.assertEquals(len(value_list), 1)

    c = bc.newContent(portal_type='Category', id='1')
    self.failUnless(c is not None)
    get_transaction().commit()
    self.tic()
    value_list = pc.getRelatedValueList(bc)
    # Now the base category should be referred to by itself and this sub category
    self.assertEquals(len(value_list), 2)
    # This sub category should be referred to only by itself
    value_list = pc.getRelatedValueList(c)
    self.assertEquals(len(value_list), 1)

    #test _getDefaultRelatedProperty Accessor
    person = self.portal.person_module.newContent(id='person_test')
    org = self.portal.organisation_module.newContent(
                                  id='organisation_test',
                                  destination='person_module/person_test')
    get_transaction().commit()
    self.tic()
    self.assertEquals(person.getDefaultDestinationRelated(),
                                  'organisation_module/organisation_test' )
Beispiel #28
0
def doPage(parent,name,text,type):
    """Create, modify or delete the specified wiki page under the parent page.

    Prints a status message and returns a boolean for success/failure.
    """
    dlog('doFile(%s,...,%s)' % (name,type))
    if options.dryrun:
        vlog(': dry run')
        return True
    existing = parent.pageWithName(name)
    #if existing and options.ignore:
    #    vlog(': ignored')
    #    return True
    if existing and options.delete:
        existing.delete(REQUEST=options.request)
        get_transaction().commit()
        vlog(': deleted')
        return True
    elif existing and options.replace:
        text = fixLinksIn(text)
        existing.edit(name, text, type, REQUEST=options.request)
        get_transaction().commit()
        vlog(': replaced')
        return True
    else:
        try:
            text = fixLinksIn(text)
            parent.create(name, text, type, REQUEST=options.request)
            get_transaction().commit()
            vlog(': created')
            return True
        except BadRequest, e:
            vlog(': failed\n*** (%s)' % e)
            return False
Beispiel #29
0
def doPage(parent, name, text, type):
    """Create, modify or delete the specified wiki page under the parent page.

    Prints a status message and returns a boolean for success/failure.
    """
    dlog('doFile(%s,...,%s)' % (name, type))
    if options.dryrun:
        vlog(': dry run')
        return True
    existing = parent.pageWithName(name)
    #if existing and options.ignore:
    #    vlog(': ignored')
    #    return True
    if existing and options.delete:
        existing.delete(REQUEST=options.request)
        get_transaction().commit()
        vlog(': deleted')
        return True
    elif existing and options.replace:
        text = fixLinksIn(text)
        existing.edit(name, text, type, REQUEST=options.request)
        get_transaction().commit()
        vlog(': replaced')
        return True
    else:
        try:
            text = fixLinksIn(text)
            parent.create(name, text, type, REQUEST=options.request)
            get_transaction().commit()
            vlog(': created')
            return True
        except BadRequest, e:
            vlog(': failed\n*** (%s)' % e)
            return False
Beispiel #30
0
  def test_decrease_and_increase_dimension(self):
    matrix = self.matrix

    cell_range = [['1', '2'], ['a', ]]
    kwd = {'base_id' : 'quantity'}
    matrix.setCellRange(*cell_range, **kwd)

    for place in cartesianProduct(cell_range):
      matrix.newCell(*place, **kwd)
    cell = matrix.getCell(*['1', 'a'], **kwd)
    get_transaction().commit()
    self.tic()
    
    cell_range = [['1', ], ['a', 'b']]
    matrix.setCellRange(*cell_range, **kwd)
    self.assertEquals(1, len(matrix.getCellValueList(**kwd)))
    # previous cell is kept
    self.assertEquals(cell, matrix.getCell(*['1', 'a'], **kwd))
    get_transaction().commit()
    self.tic()
    # the cell is still in catalog
    self.assertEquals(cell,
        self.portal.portal_catalog.getObject(cell.getUid()))
Beispiel #31
0
  def test_19_CategoryMemberValueList(self):
    """Test strict_membership parameter to Category Member Value List """
    portal_categories = self.getCategoryTool()
    organisation = self.getOrganisationModule().newContent(
              portal_type='Organisation', region='west/france')

    get_transaction().commit()
    self.tic()

    self.assertEquals([x.getObject() for x in
                        portal_categories.getCategoryMemberValueList(
                          portal_categories.region.west.france,
                          base_category='region',
                          strict_membership=0,
                          portal_type='Organisation')], [organisation])

    self.assertEquals([x.getObject() for x in
                       portal_categories.getCategoryMemberValueList(
                          portal_categories.region.west.france,
                          base_category='region',
                          strict_membership=1,
                          portal_type='Organisation')], [organisation])

    self.assertEquals([x.getObject() for x in
                       portal_categories.getCategoryMemberValueList(
                          portal_categories.region.west,
                          base_category='region',
                          strict_membership=0,
                          portal_type='Organisation')], [organisation])

    self.assertEquals([x.getObject() for x in
                      portal_categories.getCategoryMemberValueList(
                          portal_categories.region.west,
                          base_category='region',
                          strict_membership=1,
                          portal_type='Organisation')], [])
Beispiel #32
0
def doFile(context, filename, data):
    """Create, modify or delete the specified file or image.

    An Image is created if the file suffix indicates it.
    Prints a status message and returns a boolean for success/failure.
    """
    dlog('doFile(%s,...)' % (filename))
    if options.dryrun:
        vlog(': dry run')
        return True
    folder = context.folder()
    existing = getattr(folder, filename, None)
    #if existing and options.ignore:
    #    vlog(': ignored')
    #    return True
    if existing and options.delete:
        folder._delObject(filename)
        get_transaction().commit()
        vlog(': deleted')
        return True
    elif existing and options.replace:
        folder._getOb(filename).manage_upload(data)
        get_transaction().commit()
        vlog(': replaced')
        return True
    else:
        try:
            if guess_content_type(filename)[0][0:5] == 'image':
                folder._setObject(filename,
                                  OFS.Image.Image(filename, filename, ''))
            else:
                folder._setObject(filename,
                                  OFS.Image.File(filename, filename, ''))
            folder._getOb(filename).manage_upload(data)
            get_transaction().commit()
            vlog(': created')
            return True
        except BadRequest, e:
            vlog(': failed\n*** (%s)' % e)
            return False
Beispiel #33
0
def doFile(context,filename,data):
    """Create, modify or delete the specified file or image.

    An Image is created if the file suffix indicates it.
    Prints a status message and returns a boolean for success/failure.
    """
    dlog('doFile(%s,...)' % (filename))
    if options.dryrun:
        vlog(': dry run')
        return True
    folder = context.folder()
    existing = getattr(folder,filename,None)
    #if existing and options.ignore:
    #    vlog(': ignored')
    #    return True
    if existing and options.delete:
        folder._delObject(filename)
        get_transaction().commit()
        vlog(': deleted')
        return True
    elif existing and options.replace:
        folder._getOb(filename).manage_upload(data)
        get_transaction().commit()
        vlog(': replaced')
        return True
    else:
        try:
            if guess_content_type(filename)[0][0:5] == 'image':
                folder._setObject(filename, OFS.Image.Image(filename,filename,''))
            else:
                folder._setObject(filename, OFS.Image.File(filename,filename,''))
            folder._getOb(filename).manage_upload(data)
            get_transaction().commit()
            vlog(': created')
            return True
        except BadRequest, e:
            vlog(': failed\n*** (%s)' % e)
            return False
Beispiel #34
0
 def save(self):
     transaction.get_transaction().commit()
     print 'Poing db saved'
Beispiel #35
0
 def tearDown(self):
     noSecurityManager()
     get_transaction().abort()
     self.app._p_jar.close()
 def add(self, url=None, method='GET', params=None, headers=None,
         payload=_marker):
     task_id, task = make_task(url, method, params, headers, payload)
     get_transaction().join(self.transaction_data_manager(self, task))
     return task_id
 def __setitem__(self, key, value):
     if self._unregistered:
         get_transaction().join(self)
         self._unregistered = False
     return dict.__setitem__(self, key, value)
Beispiel #38
0
  def test_01_RenameCellRange(self):
    """
    tests renameCellRange behaviour
    """
    matrix = self.matrix

    cell_range = [['1', '2', '3'], ['a', 'b', 'c']]
    kwd = {'base_id' : 'quantity'}
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)

    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.newCell(portal_type="Purchase Order Cell",
                            *place, **kwd)
      cell.test_id = i
      i += 1

    cell_range = [['2', '3', '4'], ['b', 'c', 'd']]
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.getCell(*place, **kwd)
      self.assertNotEqual(cell, None)
      self.assertEqual(getattr(cell, 'test_id', None), i)
      i += 1

    cell_range = [['1', '2', '3', '4'], ['a', 'b', 'c', 'd']]
    value_list = (0, 1, 2, None, 3, 4, 5, None, 6, 7, 8, None, None, None, None, None)
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.getCell(*place, **kwd)
      if value_list[i] is None:
        self.assertEqual(cell, None)
      else:
        self.assertNotEqual(cell, None)
        self.assertEqual(getattr(cell, 'test_id', None), value_list[i])
      i += 1

    cell_range = [['1', '2'], ['a', 'b']]
    value_list = (0, 1, 3, 4)
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.getCell(*place, **kwd)
      self.assertNotEqual(cell, None)
      self.assertEqual(getattr(cell, 'test_id', None), value_list[i])
      i += 1

    cell_range = [['3'], ['a', 'b', 'c'], ['A', 'B', 'C']]
    value_list = (0, None, None, 1, None, None, None, None, None)
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.getCell(*place, **kwd)
      if value_list[i] is None:
        self.assertEqual(cell, None)
      else:
        self.assertNotEqual(cell, None)
        self.assertEqual(getattr(cell, 'test_id', None), value_list[i])
      i += 1

    cell_range = [['1', '2'], ['A', 'B']]
    value_list = (0, 1, None, None)
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.getCell(*place, **kwd)
      if value_list[i] is None:
        self.assertEqual(cell, None)
      else:
        self.assertNotEqual(cell, None)
        self.assertEqual(getattr(cell, 'test_id', None), value_list[i])
      i += 1

    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.newCell(portal_type="Purchase Order Cell",
                            *place, **kwd)
      cell.test_id = i
      i += 1

    cell_range = [['1', '2'], ['A', 'B'], ['a', 'b']]
    value_list = (0, None, 1, None, 2, None, 3, None)
    matrix.renameCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    i = 0
    for place in cartesianProduct(cell_range):
      cell = matrix.getCell(*place, **kwd)
      if value_list[i] is None:
        self.assertEqual(cell, None)
      else:
        self.assertNotEqual(cell, None)
        self.assertEqual(getattr(cell, 'test_id', None), value_list[i])
      i += 1

    # now commit transaction to make sure there are no activities for cells
    # that no longer exists.
    get_transaction().commit()
    self.tic()
 def setdefault(self, key, failobj=None):
     if self._unregistered:
         get_transaction().join(self)
         self._unregistered = False
     return dict.setdefault(self, key, failobj)
 def update(self, *args, **kw):
     if self._unregistered:
         get_transaction().join(self)
         self._unregistered = False
     return dict.update(self, *args, **kw)
Beispiel #41
0
 def __setitem__(self, key, value):
   if self._unregistered:
     get_transaction().join(self)
     self._unregistered = False
   return dict.__setitem__(self, key, value)
Beispiel #42
0
  def test_02_SetCellRangeAndCatalogWithActivities(self):
    """
    Tests if set Cell range do well catalog and uncatalog
    """
    portal = self.portal
    catalog = portal.portal_catalog

    matrix = self.matrix
    url = matrix.getUrl()

    cell_range = [['1', '2', '3'], ['a', 'b', 'c']]
    kwd = {'base_id' : 'quantity'}
    matrix.setCellRange(*cell_range, **kwd)
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)

    for place in cartesianProduct(cell_range):
      cell = matrix.newCell(portal_type="Purchase Order Cell",
                            *place, **kwd)
    get_transaction().commit()
    self.tic()
    initial_cell_id_list = list(matrix.objectIds())
    for id in initial_cell_id_list:
      self.assertTrue(catalog.hasPath(url + '/' + id))

    cell_range = [['2', '3', '4'], ['b', 'c', 'd']]
    matrix.setCellRange(*cell_range, **kwd)
    # We must commit transaction in order to put cell reindexing in activity queue
    get_transaction().commit()
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    next_cell_id_list = list(matrix.objectIds())
    # the cells on coordinates 2b, 3b, 3b and 3c are kept
    self.assertEquals(4, len(next_cell_id_list))
    for coord in [['2', 'b'],
                  ['2', 'c'],
                  ['3', 'b'],
                  ['3', 'c']]:
      self.assertNotEqual(None, matrix.getCell(*coord, **kwd))

    removed_id_list = filter(lambda x: x not in next_cell_id_list,initial_cell_id_list)
    self.tic()
    for id in next_cell_id_list:
      self.assertTrue(catalog.hasPath(url + '/' + id))
    for id in removed_id_list:
      self.assertFalse(catalog.hasPath(url + '/' + id))

    cell_range = [['0', '1'], ['a','b']]
    matrix.setCellRange(*cell_range, **kwd)
    get_transaction().commit()
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    next2_cell_id_list = list(matrix.objectIds())
    removed_id_list = filter(lambda x: x not in next2_cell_id_list,next_cell_id_list)
    self.tic()
    for id in next2_cell_id_list:
      self.assertTrue(catalog.hasPath(url + '/' + id))
    for id in removed_id_list:
      self.assertFalse(catalog.hasPath(url + '/' + id))

    cell_range = [['0', '1'], ['a','b']]
    kwd = {'base_id' : 'movement'}
    matrix.setCellRange(*cell_range, **kwd)
    get_transaction().commit()
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    self.tic()
    for id in next2_cell_id_list:
      self.assertFalse(catalog.hasPath(url + '/' + id))

    # create some cells
    cell1 = matrix.newCell(*['0', 'a'], **kwd)
    cell1_path = cell1.getPath()
    cell2 = matrix.newCell(*['1', 'a'], **kwd)
    cell2_path = cell2.getPath()
    get_transaction().commit()

    # if we keep the same range, nothing happens
    matrix.setCellRange(*cell_range, **kwd)
    get_transaction().commit()
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    self.assertEqual(len(matrix.getCellValueList(**kwd)), 2)
    self.tic()

    self.assertTrue(catalog.hasPath(matrix.getPath()))
    self.assertTrue(catalog.hasPath(cell1_path))
    self.assertTrue(catalog.hasPath(cell2_path))
  
    # now set other ranges
    cell_range = [['0', '2'], ['a', ], ['Z']]
    matrix.setCellRange(*cell_range, **kwd)
    get_transaction().commit()
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    self.tic()

    # in this case, cells has been removed
    self.assertEqual(matrix.getCellValueList(**kwd), [])

    self.assertTrue(catalog.hasPath(matrix.getPath()))
    self.assertFalse(catalog.hasPath(cell1_path))
    self.assertFalse(catalog.hasPath(cell2_path))
    
    # create cells in this new range
    cell1 = matrix.newCell(*['0', 'a', 'Z'], **kwd)
    cell1_path = cell1.getPath()
    cell2 = matrix.newCell(*['2', 'a', 'Z'], **kwd)
    cell2_path = cell2.getPath()
    get_transaction().commit()

    cell_range = [['1', '2'], ['a', ], ['X']]
    matrix.setCellRange(*cell_range, **kwd)
    get_transaction().commit()
    self.assertEqual(matrix.getCellRange(**kwd), cell_range)
    self.tic()

    # in this case, cells has been removed
    self.assertEqual(matrix.getCellValueList(**kwd), [])

    self.assertTrue(catalog.hasPath(matrix.getPath()))
    self.assertFalse(catalog.hasPath(cell1_path))
    self.assertFalse(catalog.hasPath(cell2_path))
Beispiel #43
0
 def update(self, *args, **kw):
   if self._unregistered:
     get_transaction().join(self)
     self._unregistered = False
   return dict.update(self, *args, **kw)
Beispiel #44
0
 def setdefault(self, key, failobj=None):
   if self._unregistered:
     get_transaction().join(self)
     self._unregistered = False
   return dict.setdefault(self, key, failobj)
Beispiel #45
0
def main():
    """Main procedure."""
    parseArgs()
    importFile(pageFromPath(args[0]), '.')
    get_transaction().commit()
Beispiel #46
0
 def abort(self):
     transaction.get_transaction().abort()