def test_ObjectSupport(self): # make sure listbox supports rendering of simple objects # the only requirement is that objects have a `uid` attribute which is a # string starting by new_ (a convention to prevent indexing of objects). portal = self.getPortal() list_method_id = 'DummyListMethodId' portal.ListBoxZuite_reset() form = portal.FooModule_viewFooList listbox = form.listbox listbox.ListBox_setPropertyList( field_list_method = list_method_id, field_count_method = '', field_editable_columns = ['title | title'], field_columns = ['title | Title',],) form.manage_addField('listbox_title', 'Title', 'StringField') createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, **kw', "from Products.PythonScripts.standard import Object\n" "return [Object(uid='new_', title='Object Title')]") request = get_request() request['here'] = portal.foo_module line_list = [l for l in listbox.get_value('default', render_format='list', REQUEST=request) if l.isDataLine()] self.assertEqual(1, len(line_list)) self.assertEqual('Object Title', line_list[0].getColumnProperty('title')) html = listbox.render(REQUEST=request) self.assertTrue('Object Title' in html, html)
def testUpgradeObjectWorkflowState(self): """ Create a test to ERP5Site_upgradeObjectList which aims to update Objects which are in bad workflow state or have a bad property. Signature API: { BUSINESS_TEMPLATE_TITLE : ( (OBJECT_PATH, SCRIPT TO COLLECT INFORMATION, RETURN EXPECTED THAT INDICATES THE OBJECT IS BROKEN, SCRIPT USED TO FIX ), ), } """ signature_code = {'erp5_core':( ('portal_categories/%s' % self.upgrade_object_test_id, 'getValidationState', 'embedded', 'publish'),)} createZODBPythonScript(self.getPortal().portal_skins.custom, 'ERP5Site_getUpgraderSignature', "item=None", "return " + str(signature_code)) self.commit() self.assertEqual(self.portal.ERP5Site_getUpgraderSignature(), signature_code) self.assertEqual(self.portal.ERP5Site_upgradeObjectList(), []) test_object = self.portal.portal_categories.newContent(id=self.upgrade_object_test_id, portal_type="Base Category") self.assertEqual(test_object.getValidationState(), 'embedded') self.assertNotEquals(self.portal.ERP5Site_upgradeObjectList(), []) self.assertNotEquals(self.portal.ERP5Site_upgradeObjectList(upgrade="1"), []) self.assertEqual(test_object.getValidationState(), 'published')
def test_UTF8URLColumns(self, quiet=0, run=run_all_test): """URL column script can return UTF8 encoded string """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a url column method url_column_method_id = 'Base_get%sUrlColumnMethod' % self.id() createZODBPythonScript( portal.portal_skins.custom, url_column_method_id, 'selection=None, **kw', """return u'http://example.com/?\xe9lisa'.encode('utf8')""") listbox = portal.FooModule_viewFooList.listbox # here we cover two cases, id has an editable field, title has not listbox.ListBox_setPropertyList( field_url_columns = [ 'title | %s' % url_column_method_id, 'id | %s' % url_column_method_id, ],) foo_module = portal.foo_module o = foo_module.newContent(title=u'\xe9lisa') o.immediateReindexObject() request = get_request() request['here'] = portal.foo_module try: rendered = listbox.get_value('default', render_format='list', REQUEST=request) except UnicodeError, e: self.fail('Rendering failed: %s' % e)
def test_09_expandTwoRules(self): """ test that when expand is called on a simulation movement, if two rules with the same reference are found, only the one with the higher version will be applied. XXX as expand is triggered here, make sure rules won't be created forever """ skin_folder = self.getPortal().portal_skins.custom skin = createZODBPythonScript(skin_folder, 'delivery_rule_script', 'rule', "return False") skin_folder = self.getPortal().portal_skins.custom skin = createZODBPythonScript(skin_folder, 'invoice_rule_script', 'rule', "return context.getParentValue().getSpecialiseReference() == 'default_delivery_rule'") delivery_rule = self.getRule('default_delivery_rule') delivery_rule.validate() invoicing_rule_1 = self.createRule('default_invoicing_rule', '1', test_method_id='invoice_rule_script') invoicing_rule_1.validate() invoicing_rule_2 = self.createRule('default_invoicing_rule', '2', test_method_id='invoice_rule_script') invoicing_rule_2.validate() self.pl.updateSimulation(create_root=1) self.tic() # check that only one invoicing rule (higher version) was applied root_applied_rule, = self.pl.getCausalityRelatedValueList() self.assertEquals(root_applied_rule.getSpecialise(), delivery_rule.getRelativeUrl()) movement, = root_applied_rule.objectValues() applied_rule, = movement.objectValues() self.assertEquals(applied_rule.getSpecialise(), invoicing_rule_2.getRelativeUrl()) # increase version of other rule, clean simulation and check again self.getSimulationTool()._delObject(root_applied_rule.getId()) invoicing_rule_1.setVersion('testRule.3') self.tic() self.pl.updateSimulation(create_root=1) self.tic() # check that only one invoicing rule (higher version) was applied root_applied_rule, = self.pl.getCausalityRelatedValueList() self.assertEquals(root_applied_rule.getSpecialise(), delivery_rule.getRelativeUrl()) movement, = root_applied_rule.objectValues() applied_rule, = movement.objectValues() self.assertEquals(applied_rule.getSpecialise(), invoicing_rule_1.getRelativeUrl()) self.getSimulationTool()._delObject(root_applied_rule.getId()) self.tic()
def test_02_DefaultSort(self, quiet=quiet, run=run_all_test): """Defaults sort parameters must be passed to the list method, under the 'sort_on' key. """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a list method, in this script, we will check # the sort_on parameter. list_method_id = 'ListBox_checkSortOnListMethod' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, sort_on=None, **kw', r""" if sort_on != [('title', 'ASC'), ('uid', 'ASC')]: raise AssertionError('sort_on is %r' % sort_on) return [] """) # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method = list_method_id, field_count_method = '', field_sort = 'title | ASC\n' 'uid | ASC',) # render the listbox, checks are done by list method itself request = get_request() request['here'] = portal.foo_module listbox.get_value('default', render_format='list', REQUEST=request)
def test_072_search_with_extra_catalog_keywords(self): """ test that a category criteria on a rule that doesn't have that category allows the rule to match contexts with and without that category """ skin_folder = self.getPortal().portal_skins.custom rule_tool = self.getRuleTool() # add an always-matching predicate test script to the rule createZODBPythonScript(skin_folder, 'good_script', 'rule', 'return True') delivery_rule = self.getRule('default_delivery_rule') delivery_rule.setTestMethodId('good_script') delivery_rule.validate() self.tic() # Now since the rule has a trade_phase trade_phase_list = delivery_rule.getTradePhaseList() self.assertEqual(trade_phase_list, ['default/delivery']) # then it should be possible to find it by passing this trade_phase # as an additional catalog keyword kw = {'trade_phase_relative_url': ['trade_phase/' + path for path in trade_phase_list]} # XXX-Leo: Fugly catalog syntax for category search above. self.assertEqual(len(rule_tool.searchRuleList(self.sm, **kw)), 1) # and also not to match it if we pass a different trade_phase kw['trade_phase_relative_url'] = ['trade_phase/' + 'default/order'] self.assertEqual(len(rule_tool.searchRuleList(self.sm, **kw)), 0) # but match it again if we pass an empty list for trade_phase # (with a warning in the log about discarding empty values) kw['trade_phase_relative_url'] = [] self.assertEqual(len(rule_tool.searchRuleList(self.sm, **kw)), 1)
def test_09_expandTwoRules(self): """ test that when expand is called on a simulation movement, if two rules with the same reference are found, only the one with the higher version will be applied. XXX as expand is triggered here, make sure rules won't be created forever """ skin_folder = self.getPortal().portal_skins.custom skin = createZODBPythonScript(skin_folder, 'delivery_rule_script', 'rule', "return False") skin_folder = self.getPortal().portal_skins.custom skin = createZODBPythonScript(skin_folder, 'invoice_rule_script', 'rule', "return context.getParentValue().getSpecialiseReference() == 'default_delivery_rule'") delivery_rule = self.getRule('default_delivery_rule') delivery_rule.validate() invoicing_rule_1 = self.createRule('default_invoicing_rule', '1', test_method_id='invoice_rule_script') invoicing_rule_1.validate() invoicing_rule_2 = self.createRule('default_invoicing_rule', '2', test_method_id='invoice_rule_script') invoicing_rule_2.validate() self.pl.updateSimulation(create_root=1) self.tic() # check that only one invoicing rule (higher version) was applied root_applied_rule, = self.pl.getCausalityRelatedValueList() self.assertEqual(root_applied_rule.getSpecialise(), delivery_rule.getRelativeUrl()) movement, = root_applied_rule.objectValues() applied_rule, = movement.objectValues() self.assertEqual(applied_rule.getSpecialise(), invoicing_rule_2.getRelativeUrl()) # increase version of other rule, clean simulation and check again self.getSimulationTool()._delObject(root_applied_rule.getId()) invoicing_rule_1.setVersion('testRule.3') self.tic() self.pl.updateSimulation(create_root=1) self.tic() # check that only one invoicing rule (higher version) was applied root_applied_rule, = self.pl.getCausalityRelatedValueList() self.assertEqual(root_applied_rule.getSpecialise(), delivery_rule.getRelativeUrl()) movement, = root_applied_rule.objectValues() applied_rule, = movement.objectValues() self.assertEqual(applied_rule.getSpecialise(), invoicing_rule_1.getRelativeUrl()) self.getSimulationTool()._delObject(root_applied_rule.getId()) self.tic()
def test_predicateIndexation(self): predicate = self.createPredicate( membership_criterion_base_category_list=['region'], membership_criterion_category_list=[REGION_FRANCE_PATH]) # Our test document will only be a predicate if title is different # from 'never applies' createZODBPythonScript( self.portal.portal_skins.custom, 'Predicate_asPredicate', '', """return None if context.getTitle() == 'never applies' else context""" ) self.tic() self.assertEqual([predicate], [ brain.getObject() for brain in self.portal.portal_catalog( **{'predicate.uid': predicate.getUid()}) ]) self.assertEqual([predicate], [ brain.getObject() for brain in self.portal.portal_catalog( **{'predicate_category.uid': predicate.getUid()}) ]) predicate.setTitle("never applies") # this predicate is no longer a predicate, so it no longer exist in predicate tables self.tic() self.assertEqual([], [ brain.getObject() for brain in self.portal.portal_catalog( **{'predicate.uid': predicate.getUid()}) ]) self.assertEqual([], [ brain.getObject() for brain in self.portal.portal_catalog( **{'predicate_category.uid': predicate.getUid()}) ])
def test_UpgradeWorkflowChain(self): """ Upgrade the workflow chain if required. """ workflow_tool = self.portal.portal_workflow workflow_dict = workflow_tool.getWorkflowChainDict() signature_code = workflow_dict createZODBPythonScript(self.getPortal().portal_skins.custom, 'ERP5Site_getUpgraderSignature', "item=None", "return " + str(signature_code)) self.commit() self.assertEqual(self.portal.ERP5Site_upgradeWorkflowChain(), []) original_person_chain = workflow_dict["chain_Person"] # Modify installed workflow chain. workflow_dict["chain_Person"] = '' workflow_tool.manage_changeWorkflows(default_chain = '', props = workflow_dict) self.assertEqual(workflow_tool.getWorkflowChainDict()["chain_Person"], "") self.assertEqual(self.portal.ERP5Site_upgradeWorkflowChain(), ["Upgrade Required for Workflow Chain."]) self.assertEqual(self.portal.ERP5Site_upgradeWorkflowChain(upgrade=1), ["Upgrade Executed for Workflow Chain."]) self.tic() self.assertEqual(self.portal.ERP5Site_upgradeWorkflowChain(),[]) self.assertEqual(workflow_tool.getWorkflowChainDict()["chain_Person"], original_person_chain)
def test_04_UnicodeParameters(self, quiet=0, run=run_all_test): """Unicode properties are handled. """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a list method list_method_id = 'ListBox_ParametersListMethod' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, **kw', """return [context.asContext(alternate_title = u'\xe9lisa')]""") # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method=list_method_id, field_count_method='', field_columns=[ 'alternate_title | Alternate Title', ], ) request = get_request() request['here'] = portal.foo_module try: listbox.get_value('default', render_format='list', REQUEST=request) except UnicodeError, e: self.fail('Rendering failed: %s' % e)
def afterSetUp(self): super(TestRenderUpdateTranslationData, self).afterSetUp() # create a translation script for this web site self.web_script_translation_data_js = self.portal.web_page_module.newContent( portal_type='Web Script', # the convention is that this script has suffix translation_data.js reference='{}_translation_data.js'.format(self.id()), text_content='// will be filled', ) self.web_script_translation_data_js.publish() self.web_page_translation_gadget = self.portal.web_page_module.newContent( portal_type='Web Page', reference='{}_translation.html'.format(self.id()), content_type='text/html', text_content=textwrap.dedent(''' <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Translation Gadget</title> <link rel="http://www.renderjs.org/rel/interface" href="interface_translation.html"> <!-- renderjs --> <script src="rsvp.js" type="text/javascript"></script> <script src="renderjs.js" type="text/javascript"></script> <!-- custom script --> <script src="{translation_data_js_reference}" type="text/javascript"></script> <script src="gadget_translation.js" type="text/javascript"></script> </head> <body> </body> </html> ''').format(translation_data_js_reference=self. web_script_translation_data_js.getReference()), ) self.web_page_translation_gadget.publish() self.web_site.setProperty( 'configuration_translation_gadget_url', self.web_page_translation_gadget.getReference()) self.web_site.setAvailableLanguageList(['en', 'fa']) # add a manifest to list web pages to extract messages from createZODBPythonScript( self.portal.portal_skins.custom, 'WebSection_getTestPrecacheManifestList', '', textwrap.dedent(''' return [ 'test_gadget_with_translation.html', 'test_gadget_with_translation.js', 'test_portal_skins_gadget.html', ] ''')) self.web_site.setProperty( 'configuration_precache_manifest_script_list', 'WebSection_getTestPrecacheManifestList') self.tic()
def test_UTF8URLColumns(self, quiet=0, run=run_all_test): """URL column script can return UTF8 encoded string """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a url column method url_column_method_id = 'Base_get%sUrlColumnMethod' % self.id() createZODBPythonScript( portal.portal_skins.custom, url_column_method_id, 'selection=None, **kw', """return u'http://example.com/?\xe9lisa'.encode('utf8')""") listbox = portal.FooModule_viewFooList.listbox # here we cover two cases, id has an editable field, title has not listbox.ListBox_setPropertyList(field_url_columns=[ 'title | %s' % url_column_method_id, 'id | %s' % url_column_method_id, ], ) foo_module = portal.foo_module o = foo_module.newContent(title=u'\xe9lisa') o.immediateReindexObject() request = get_request() request['here'] = portal.foo_module try: rendered = listbox.get_value('default', render_format='list', REQUEST=request) except UnicodeError, e: self.fail('Rendering failed: %s' % e)
def test_MaximumRecursionDepthExceededWithComplexSecurity(self): skin = self.portal.portal_skins.custom colour = self.portal.portal_categories.colour colour.hasObject('green') or colour.newContent('green') login = str(time.time()) script_id = ["ERP5Type_getSecurityCategoryMapping", "ERP5Type_getSecurityCategory"] createZODBPythonScript(skin, script_id[0], "", "return ((%r, ('colour',)),)" % script_id[1]) createZODBPythonScript(skin, script_id[1], "base_category_list, user_name, object, portal_type, depth=[]", """if 1: # This should not be called recursively, or at least if should not fail. # Because RuntimeError is catched by 'except:' clauses, we detect it # with a static variable. depth.append(None) assert not portal_type, portal_type # the following line calls Base_zSearchRelatedObjectsByCategoryList object.getSourceDecisionRelatedValueList() bc, = base_category_list depth.pop() return [] if depth else [{bc: 'green'}] """) person = self.portal.person_module.newContent(reference=login) try: self.tic() PortalTestCase.login(self, person.Person_getUserId()) self.assertEqual(['green'], getSecurityManager().getUser().getGroups()) self.portal.portal_caches.clearAllCache() PortalTestCase.login(self, person.Person_getUserId()) unittest.expectedFailure(self.assertEqual)( ['green'], getSecurityManager().getUser().getGroups()) finally: skin.manage_delObjects(script_id) self.commit()
def test_MaximumRecursionDepthExceededWithComplexSecurity(self): skin = self.portal.portal_skins.custom colour = self.portal.portal_categories.colour if not colour.hasObject('green'): colour.newContent('green') login = str(time.time()) script_id = ["ERP5Type_getSecurityCategoryMapping", "ERP5Type_getSecurityCategory"] createZODBPythonScript(skin, script_id[0], "", "return ((%r, ('colour',)),)" % script_id[1]) createZODBPythonScript(skin, script_id[1], "base_category_list, user_name, object, portal_type, depth=[]", """if 1: # This should not be called recursively, or at least if should not fail. # Because RuntimeError is catched by 'except:' clauses, we detect it # with a static variable. depth.append(None) assert not portal_type, portal_type object.getSourceDecisionRelatedValueList() bc, = base_category_list depth.pop() return [] if depth else [{bc: 'green'}] """) person = self.portal.person_module.newContent(reference=login) try: self.tic() PortalTestCase.login(self, person.Person_getUserId()) self.assertEqual(['green'], getSecurityManager().getUser().getGroups()) self.portal.portal_caches.clearAllCache() PortalTestCase.login(self, person.Person_getUserId()) self.assertEqual( ['green'], getSecurityManager().getUser().getGroups()) finally: skin.manage_delObjects(script_id) self.commit()
def test_03_DefaultParameters(self, quiet=quiet, run=run_all_test): """Defaults parameters are passed as keyword arguments to the list method """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a list method, in this script, we will check # the default parameter. list_method_id = 'ListBox_checkDefaultParametersListMethod' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, dummy_default_param=None, **kw', """ if dummy_default_param != 'dummy value': raise AssertionError('recieved wrong arguments: %s instead of "dummy value"' % dummy_default_param ) return [] """) # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method = list_method_id, field_count_method = '', field_default_params = 'dummy_default_param | dummy value',) # render the listbox, checks are done by list method itself request = get_request() request['here'] = portal.foo_module listbox.get_value('default', render_format='list', REQUEST=request)
def test_072_search_with_extra_catalog_keywords(self): """ test that a category criteria on a rule that doesn't have that category allows the rule to match contexts with and without that category """ skin_folder = self.getPortal().portal_skins.custom rule_tool = self.getRuleTool() # add an always-matching predicate test script to the rule createZODBPythonScript(skin_folder, 'good_script', 'rule', 'return True') delivery_rule = self.getRule('default_delivery_rule') delivery_rule.setTestMethodId('good_script') delivery_rule.validate() self.tic() # Now since the rule has a trade_phase trade_phase_list = delivery_rule.getTradePhaseList() self.assertEqual(trade_phase_list, ['trade/delivery']) # then it should be possible to find it by passing this trade_phase # as an additional catalog keyword kw = { 'trade_phase_relative_url': ['trade_phase/' + path for path in trade_phase_list] } # XXX-Leo: Fugly catalog syntax for category search above. self.assertEqual(len(rule_tool.searchRuleList(self.sm, **kw)), 1) # and also not to match it if we pass a different trade_phase kw['trade_phase_relative_url'] = ['trade_phase/trade/order'] self.assertEqual(len(rule_tool.searchRuleList(self.sm, **kw)), 0) # but match it again if we pass an empty list for trade_phase # (with a warning in the log about discarding empty values) kw['trade_phase_relative_url'] = [] self.assertEqual(len(rule_tool.searchRuleList(self.sm, **kw)), 1)
def test_04_UnicodeParameters(self, quiet=0, run=run_all_test): """Unicode properties are handled. """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a list method list_method_id = 'ListBox_ParametersListMethod' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, **kw', """return [context.asContext(alternate_title = u'\xe9lisa')]""") # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method = list_method_id, field_count_method = '', field_columns = ['alternate_title | Alternate Title',],) request = get_request() request['here'] = portal.foo_module try: listbox.get_value('default', render_format='list', REQUEST=request) except UnicodeError, e: self.fail('Rendering failed: %s' % e)
def afterSetUp(self): """Called after setup completed. """ self.portal = self.getPortal() # create a security configuration script skin_folder = self.portal.portal_skins.custom if "ERP5Type_getSecurityCategoryMapping" not in skin_folder.objectIds(): createZODBPythonScript( skin_folder, "ERP5Type_getSecurityCategoryMapping", "", """return (( 'ERP5Type_getSecurityCategoryFromAssignment', context.getPortalObject().getPortalAssignmentBaseCategoryList() ),) """, ) # configure group, site, function categories for bc in ["group", "site", "function"]: base_cat = self.getCategoryTool()[bc] code = bc[0].upper() base_cat.newContent(portal_type="Category", id="subcat", codification="%s1" % code) # add another function subcategory. self.getCategoryTool()["function"].newContent(portal_type="Category", id="another_subcat", codification="F2") self.defined_category = "group/subcat\n" "site/subcat\n" "function/subcat" # any member can add organisations self.portal.organisation_module.manage_permission("Add portal content", roles=["Member", "Manager"], acquire=1) self.username = "******" # create a user and open an assignement pers = self.getPersonModule().newContent(portal_type="Person", reference=self.username, password=self.username) assignment = pers.newContent(portal_type="Assignment", group="subcat", site="subcat", function="subcat") assignment.open() transaction.commit() self.tic()
def test_ObjectSupport(self): # make sure listbox supports rendering of simple objects # the only requirement is that objects have a `uid` attribute which is a # string starting by new_ (a convention to prevent indexing of objects). portal = self.getPortal() list_method_id = 'DummyListMethodId' portal.ListBoxZuite_reset() form = portal.FooModule_viewFooList listbox = form.listbox listbox.ListBox_setPropertyList( field_list_method = list_method_id, field_count_method = '', field_editable_columns = ['title | title'], field_columns = ['title | Title',],) form.manage_addField('listbox_title', 'Title', 'StringField') createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, **kw', "from Products.PythonScripts.standard import Object\n" "return [Object(uid='new_', title='Object Title')]") request = get_request() request['here'] = portal.foo_module line_list = [l for l in listbox.get_value('default', render_format='list', REQUEST=request) if l.isDataLine()] self.assertEquals(1, len(line_list)) self.assertEquals('Object Title', line_list[0].getColumnProperty('title')) html = listbox.render(REQUEST=request) self.failUnless('Object Title' in html, html)
def test_zodb_timeout(self): portal = self.getPortal() portal.ListBoxZuite_reset() # Set short enough publisher timeout configuration import Products.ERP5Type.Timeout Products.ERP5Type.Timeout.publisher_timeout = 2.0 # We create a Z SQL Method that takes too long list_method_id = 'ListBox_getSlowObjectValues' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, **kw', """ from time import sleep sleep(3) return context.objectValues() """) # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method=list_method_id, field_count_method='', ) portal.foo_module.newContent() # access the form result = self.publish( '%s/FooModule_viewFooList' % portal.foo_module.absolute_url(relative=True), 'ERP5TypeTestCase:', ) self.assertEqual(result.getStatus(), 500) self.assertIn('Error Type: TimeoutReachedError', result.getBody())
def test_UpgradeWorkflowChain(self): """ Upgrade the workflow chain if required. """ workflow_tool = self.portal.portal_workflow workflow_dict = workflow_tool.getWorkflowChainDict() signature_code = workflow_dict createZODBPythonScript(self.getPortal().portal_skins.custom, 'ERP5Site_getUpgraderSignature', "item=None", "return " + str(signature_code)) self.commit() self.assertEquals(self.portal.ERP5Site_upgradeWorkflowChain(), []) original_person_chain = workflow_dict["chain_Person"] # Modify installed workflow chain. workflow_dict["chain_Person"] = '' workflow_tool.manage_changeWorkflows(default_chain = '', props = workflow_dict) self.assertEquals(workflow_tool.getWorkflowChainDict()["chain_Person"], "") self.assertEquals(self.portal.ERP5Site_upgradeWorkflowChain(), ["Upgrade Required for Workflow Chain."]) self.assertEquals(self.portal.ERP5Site_upgradeWorkflowChain(upgrade=1), ["Upgrade Executed for Workflow Chain."]) self.tic() self.assertEquals(self.portal.ERP5Site_upgradeWorkflowChain(),[]) self.assertEquals(workflow_tool.getWorkflowChainDict()["chain_Person"], original_person_chain)
def testUpgradeObjectWorkflowState(self): """ Create a test to ERP5Site_upgradeObjectList which aims to update Objects which are in bad workflow state or have a bad property. Signature API: { BUSINESS_TEMPLATE_TITLE : ( (OBJECT_PATH, SCRIPT TO COLLECT INFORMATION, RETURN EXPECTED THAT INDICATES THE OBJECT IS BROKEN, SCRIPT USED TO FIX ), ), } """ signature_code = {'erp5_core':( ('portal_categories/%s' % self.upgrade_object_test_id, 'getValidationState', 'embedded', 'publish'),)} createZODBPythonScript(self.getPortal().portal_skins.custom, 'ERP5Site_getUpgraderSignature', "item=None", "return " + str(signature_code)) self.commit() self.assertEquals(self.portal.ERP5Site_getUpgraderSignature(), signature_code) self.assertEquals(self.portal.ERP5Site_upgradeObjectList(), []) test_object = self.portal.portal_categories.newContent(id=self.upgrade_object_test_id, portal_type="Base Category") self.assertEquals(test_object.getValidationState(), 'embedded') self.assertNotEquals(self.portal.ERP5Site_upgradeObjectList(), []) self.assertNotEquals(self.portal.ERP5Site_upgradeObjectList(upgrade="1"), []) self.assertEquals(test_object.getValidationState(), 'published')
def test_02_DefaultSort(self, quiet=quiet, run=run_all_test): """Defaults sort parameters must be passed to the list method, under the 'sort_on' key. """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a list method, in this script, we will check # the sort_on parameter. list_method_id = 'ListBox_checkSortOnListMethod' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, sort_on=None, **kw', textwrap.dedent(r""" if sort_on != [('title', 'ASC'), ('uid', 'ASC')]: raise AssertionError('sort_on is %r' % sort_on) return [] """)) # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method=list_method_id, field_count_method='', field_sort='title | ASC\n' 'uid | ASC', ) # render the listbox, checks are done by list method itself request = get_request() request['here'] = portal.foo_module listbox.get_value('default', render_format='list', REQUEST=request)
def test_03_DefaultParameters(self, quiet=quiet, run=run_all_test): """Defaults parameters are passed as keyword arguments to the list method """ portal = self.getPortal() portal.ListBoxZuite_reset() # We create a script to use as a list method, in this script, we will check # the default parameter. list_method_id = 'ListBox_checkDefaultParametersListMethod' createZODBPythonScript( portal.portal_skins.custom, list_method_id, 'selection=None, dummy_default_param=None, **kw', textwrap.dedent(""" if dummy_default_param != 'dummy value': raise AssertionError('recieved wrong arguments: %s instead of "dummy value"' % dummy_default_param ) return [] """)) # set the listbox to use this as list method listbox = portal.FooModule_viewFooList.listbox listbox.ListBox_setPropertyList( field_list_method=list_method_id, field_count_method='', field_default_params='dummy_default_param | dummy value', ) # render the listbox, checks are done by list method itself request = get_request() request['here'] = portal.foo_module listbox.get_value('default', render_format='list', REQUEST=request)
def _simulatePaymentTransaction_getTotalPayablePrice(self): script_name = 'PaymentTransaction_getTotalPayablePrice' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\nreturn %f' % HARDCODED_PRICE)
def _simulatePaymentTransaction_getRecentPayzenId(self): script_name = 'PaymentTransaction_getPayzenId' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """return DateTime().toZone('UTC'), 'foo'""")
def test_070_direct_criteria_specification(self): """ test that rule-specific scripts can specify identity and range criteria """ skin_folder = self.getPortal().portal_skins.custom # add an always-matching predicate test script to the rule createZODBPythonScript(skin_folder, 'good_script', 'rule', 'return True') delivery_rule = self.getRule('default_delivery_rule') delivery_rule.setTestMethodId('good_script') # but add a predicate building script that only matches on # Simulation Movements, to affect all rules createZODBPythonScript(skin_folder, 'RuleMixin_asPredicate', '', """ return context.generatePredicate( identity_criterion=dict(portal_type=(context.movement_type,)), ) """) # and validate it, which will indirectly reindex the predicate. delivery_rule.validate() self.tic() # now rules don't match packing lists by default self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 0) # only simulation movements self.assertEqual(len(self.getRuleTool().searchRuleList(self.sm)), 1) # unless they have more specific predicate script telling them otherwise: predicate_script = createZODBPythonScript( skin_folder, 'DeliveryRootSimulationRule_asPredicate', '', """ return context.generatePredicate( identity_criterion=dict(portal_type=('Sale Packing List',)), range_criterion=dict(start_date=(%r, None)), ) """ % self.pl.getStartDate()) delivery_rule.reindexObject() self.tic() # now they match the packing list, but not the simulation movement self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 1) self.assertEqual(len(self.getRuleTool().searchRuleList(self.sm)), 0) # Note that we added a range criterion above, which means that if # the packing list no longer falls within the range... self.pl.setStartDate(self.pl.getStartDate() - 1) self.tic() # ... then the rule no longer matches the packing list: self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 0) # But if we push back the date on the criterion... predicate_script.write(""" return context.generatePredicate( identity_criterion=dict(portal_type=('Sale Packing List',)), range_criterion=dict(start_date=(%r, None)), ) """ % self.pl.getStartDate()) delivery_rule.reindexObject() self.tic() # ... it will match again self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 1)
def test_070_direct_criteria_specification(self): """ test that rule-specific scripts can specify identity and range criteria """ skin_folder = self.getPortal().portal_skins.custom # add an always-matching predicate test script to the rule createZODBPythonScript(skin_folder, 'good_script', 'rule', 'return True') delivery_rule = self.getRule('default_delivery_rule') delivery_rule.setTestMethodId('good_script') # but add a predicate building script that only matches on # Simulation Movements, to affect all rules createZODBPythonScript(skin_folder, 'RuleMixin_asPredicate', '', """ return context.generatePredicate( identity_criterion=dict(portal_type=(context.movement_type,)), ) """) # and validate it, which will indirectly reindex the predicate. delivery_rule.validate() self.tic() # now rules don't match packing lists by default self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 0) # only simulation movements self.assertEqual(len(self.getRuleTool().searchRuleList(self.sm)), 1) # unless they have more specific predicate script telling them otherwise: predicate_script = createZODBPythonScript( skin_folder, 'DeliveryRootSimulationRule_asPredicate', '', """ return context.generatePredicate( identity_criterion=dict(portal_type=('Sale Packing List',)), range_criterion=dict(start_date=(%r, None)), ) """ % self.pl.getStartDate()) delivery_rule.reindexObject() self.tic() # now they match the packing list, but not the simulation movement self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 1) self.assertEqual(len(self.getRuleTool().searchRuleList(self.sm)), 0) # Note that we added a range criterion above, which means that if # the packing list no longer falls within the range... self.pl.setStartDate(self.pl.getStartDate() - 1) self.tic() # ... then the rule no longer matches the packing list: self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 0) # But if we push back the date on the criterion... predicate_script.write(""" return context.generatePredicate( identity_criterion=dict(portal_type=('Sale Packing List',)), range_criterion=dict(start_date=(%r, None)), ) """ % self.pl.getStartDate()) delivery_rule.reindexObject() self.tic() # ... it will match again self.assertEqual(len(self.getRuleTool().searchRuleList(self.pl)), 1)
def _simulateScript(self, script_name): if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """portal_workflow = context.portal_workflow portal_workflow.doActionFor(context, action='edit_action', comment='Visited by %s') """ % script_name ) transaction.commit()
def _simulatePerson_isNotAllowedToAllocate(self): script_name = 'Person_isAllowedToAllocate' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """return False""") transaction.commit()
def createUpdateScriptPersonUpdateTitleFromJSON(self): createZODBPythonScript( self.portal.portal_skins.custom, "Person_updateTitleFromJSON", "data, list_error", """ import json context.setTitle(data['title']) return json.dumps({ "id": context.getRelativeUrl() }, indent=2) """)
def createUpdateScriptPersonAsBasicJSON(self): createZODBPythonScript( self.portal.portal_skins.custom, "Person_asBasicJSON", "text_data, list_error", """ import json return json.dumps({ "id": context.getRelativeUrl(), "title": context.getTitle(), }, indent=2) """)
def stepCreateAsTextScript(self, sequence=None, **kw): """ This script returns a different address format. """ createZODBPythonScript( self.getPortal().portal_skins.custom, 'Address_asText', '', """ return '%s\\n%s %s COUNTRY' % \\ (context.getStreetAddress(), context.getZipCode(), context.getCity()) """)
def stepCreateAsTextScript(self, sequence=None, **kw) : """ This script returns a different address format. """ createZODBPythonScript(self.getPortal().portal_skins.custom, 'Address_asText', '', """ return '%s\\n%s %s COUNTRY' % \\ (context.getStreetAddress(), context.getZipCode(), context.getCity()) """)
def _simulatePaymentTransaction_getOldPayzenId(self): script_name = 'PaymentTransaction_getPayzenId' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """from Products.ERP5Type.DateUtils import addToDate return addToDate(DateTime(), to_add={'day': -1, 'second': -1}).toZone('UTC'), 'foo'""")
def testJupyterCompileErrorRaise(self): """ Test if JupyterCompile portal_component correctly catches exceptions as expected by the Jupyter frontend as also automatically abort the current transaction. Take the case in which one line in a statement is valid and another is not. """ portal = self.getPortalObject() script_id = "JupyterCompile_errorResult" script_container = portal.portal_skins.custom new_test_title = "Wendelin Test 1" # Check if the existing title is different from new_test_title or not if portal.getTitle()==new_test_title: new_test_title = "Wendelin" python_script = """ portal = context.getPortalObject() portal.setTitle('%s') print an_undefined_variable """%new_test_title # Create python_script object with the above given code and containers createZODBPythonScript(script_container, script_id, '', python_script) self.tic() # Call the above created script in jupyter_code jupyter_code = """ portal = context.getPortalObject() portal.%s() """%script_id # Make call to Base_runJupyter to run the jupyter code which is making # a call to the newly created ZODB python_script and assert if the call # processes correctly the NameError as we are sending an invalid # python_code to it. # result = portal.Base_runJupyter( jupyter_code=jupyter_code, old_notebook_context=portal.Base_createNotebookContext() ) self.assertEquals(result['ename'], 'NameError') self.assertEquals(result['result_string'], None) # There's no need to abort the current transaction. The error handling code # should be responsible for this, so we check the script's title script_title = script_container.JupyterCompile_errorResult.getTitle() self.assertNotEqual(script_title, new_test_title) removeZODBPythonScript(script_container, script_id) # Test that calling Base_runJupyter shouldn't change the context Title self.assertNotEqual(portal.getTitle(), new_test_title)
def test_request_with_x_forwarded_for(self): script_container = self.portal.portal_skins.custom script_id = 'ERP5Site_getClientAddr' createZODBPythonScript(script_container, script_id, '', 'return context.REQUEST.getClientAddr()') self.commit() import ZPublisher.HTTPRequest # test without configuration ZPublisher.HTTPRequest.trusted_proxies = [] response = requests.get( '%s/%s' % (self.portal.absolute_url(), script_id), headers={'X-Forwarded-For': '1.2.3.4'}, ) self.assertNotEqual(response.text, '1.2.3.4') last_line = get_Z2_log_last_line() self.assertFalse(last_line.startswith('1.2.3.4 - '), last_line) response = requests.get( '%s/%s' % (self.portal.absolute_url(), script_id), headers={'X-Forwarded-For': '1.2.3.4, 5.6.7.8'}, ) self.assertNotEqual(response.text, '1.2.3.4') self.assertNotEqual(response.text, '5.6.7.8') last_line = get_Z2_log_last_line() self.assertFalse(last_line.startswith('1.2.3.4 - '), last_line) self.assertFalse(last_line.startswith('5.6.7.8 - '), last_line) response = requests.get( '%s/%s' % (self.portal.absolute_url(), script_id), ) self.assertNotEqual(response.text, '1.2.3.4') last_line = get_Z2_log_last_line() self.assertFalse(last_line.startswith('1.2.3.4 - '), last_line) # test with configuration ZPublisher.HTTPRequest.trusted_proxies = ('0.0.0.0',) response = requests.get( '%s/%s' % (self.portal.absolute_url(), script_id), headers={'X-Forwarded-For': '1.2.3.4'}, ) self.assertEqual(response.text, '1.2.3.4') last_line = get_Z2_log_last_line() self.assertTrue(last_line.startswith('1.2.3.4 - '), last_line) response = requests.get( '%s/%s' % (self.portal.absolute_url(), script_id), headers={'X-Forwarded-For': '1.2.3.4, 5.6.7.8'}, ) self.assertEqual(response.text, '1.2.3.4') last_line = get_Z2_log_last_line() self.assertTrue(last_line.startswith('1.2.3.4 - '), last_line) response = requests.get( '%s/%s' % (self.portal.absolute_url(), script_id), ) self.assertNotEqual(response.text, '1.2.3.4') last_line = get_Z2_log_last_line() self.assertFalse(last_line.startswith('1.2.3.4 - '), last_line)
def test_08_updateLastMaxIdDictFromTable(self): """ Check that it can update id_dict persistent object from portal_ids table. Also, check that it can update more than 1000 keys. """ id_generator = 'test_application_sql' sql_generator = self.getLastGenerator(id_generator) sql_generator.setStoredInZodb(False) self.assertEqual(0, self.id_tool.generateNewId(id_generator=id_generator, id_group='A-08')) self.assertEqual(1, self.id_tool.generateNewId(id_generator=id_generator, id_group='A-08')) self.assertEqual(2, self.id_tool.generateNewId(id_generator=id_generator, id_group='A-08')) self.assertEqual(0, self.id_tool.generateNewId(id_generator=id_generator, id_group='B-08')) self.assertEqual(1, self.id_tool.generateNewId(id_generator=id_generator, id_group='B-08')) A_LOT_OF_KEY = 2500 var_id = 'C-%04d' for x in xrange(A_LOT_OF_KEY): self.assertEqual(0, self.id_tool.generateNewId(id_generator=id_generator, id_group=var_id % x)) # test before update self.assertEqual(None, sql_generator.last_max_id_dict.get('A-08')) self.assertEqual(None, sql_generator.last_max_id_dict.get('B-08')) for x in xrange(A_LOT_OF_KEY): self.assertEqual(None, sql_generator.last_max_id_dict.get(var_id % x)) createZODBPythonScript( self.portal.portal_skins.custom, 'IdTool_updateLastMaxId', 'last_id_group=None', r""" id_tool = context.getPortalObject().portal_ids sql_generator = id_tool.searchFolder( reference='test_sql_non_continuous_increasing')[0].getLatestVersionValue() new_last_id_group = sql_generator.updateLastMaxIdDictFromTable(last_id_group) if new_last_id_group is not None: getattr(context.activate(), script.id)(new_last_id_group) """) # update dict from sql with activities sql_generator.IdTool_updateLastMaxId() self.tic() # asserts self.assertEqual(2, sql_generator.last_max_id_dict['A-08'].value) self.assertEqual(1, sql_generator.last_max_id_dict['B-08'].value) for x in xrange(A_LOT_OF_KEY): self.assertEqual(0, sql_generator.last_max_id_dict[var_id % x].value)
def _simulateComputer_checkAndUpdateCapacityScope(self): script_name = 'Computer_checkAndUpdateCapacityScope' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """portal_workflow = context.portal_workflow portal_workflow.doActionFor(context, action='edit_action', comment='Visited by Computer_checkAndUpdateCapacityScope') """ ) transaction.commit()
def _simulateActiveProcess_deleteSelf(self): script_name = 'ActiveProcess_deleteSelf' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """description = '%s\\nVisited by ActiveProcess_deleteSelf' % context.getDescription() context.edit(description=description)""") transaction.commit()
def test_08_updateLastMaxIdDictFromTable(self): """ Check that it can update id_dict persistent object from portal_ids table. Also, check that it can update more than 1000 keys. """ id_generator = 'test_application_sql' sql_generator = self.getLastGenerator(id_generator) sql_generator.setStoredInZodb(False) self.assertEquals(0, self.id_tool.generateNewId(id_generator=id_generator, id_group='A-08')) self.assertEquals(1, self.id_tool.generateNewId(id_generator=id_generator, id_group='A-08')) self.assertEquals(2, self.id_tool.generateNewId(id_generator=id_generator, id_group='A-08')) self.assertEquals(0, self.id_tool.generateNewId(id_generator=id_generator, id_group='B-08')) self.assertEquals(1, self.id_tool.generateNewId(id_generator=id_generator, id_group='B-08')) A_LOT_OF_KEY = 2500 var_id = 'C-%04d' for x in xrange(A_LOT_OF_KEY): self.assertEquals(0, self.id_tool.generateNewId(id_generator=id_generator, id_group=var_id % x)) # test before update self.assertEquals(None, sql_generator.last_max_id_dict.get('A-08')) self.assertEquals(None, sql_generator.last_max_id_dict.get('B-08')) for x in xrange(A_LOT_OF_KEY): self.assertEquals(None, sql_generator.last_max_id_dict.get(var_id % x)) createZODBPythonScript( self.portal.portal_skins.custom, 'IdTool_updateLastMaxId', 'last_id_group=None', r""" id_tool = context.getPortalObject().portal_ids sql_generator = id_tool.searchFolder( reference='test_sql_non_continuous_increasing')[0].getLatestVersionValue() new_last_id_group = sql_generator.updateLastMaxIdDictFromTable(last_id_group) if new_last_id_group is not None: getattr(context.activate(), script.id)(new_last_id_group) """) # update dict from sql with activities sql_generator.IdTool_updateLastMaxId() self.tic() # asserts self.assertEquals(2, sql_generator.last_max_id_dict['A-08'].value) self.assertEquals(1, sql_generator.last_max_id_dict['B-08'].value) for x in xrange(A_LOT_OF_KEY): self.assertEquals(0, sql_generator.last_max_id_dict[var_id % x].value)
def _simulateHostingSubscription_calculateSubscriptionStartDate(self, date): script_name = 'HostingSubscription_calculateSubscriptionStartDate' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """from DateTime import DateTime return DateTime('%s') """ % date.ISO()) transaction.commit()
def _simulatePerson_checkToCreateRegularisationRequest(self): script_name = 'Person_checkToCreateRegularisationRequest' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """portal_workflow = context.portal_workflow portal_workflow.doActionFor(context, action='edit_action', comment='Visited by Person_checkToCreateRegularisationRequest') """ ) transaction.commit()
def testJupyterCompileErrorRaise(self): """ Test if JupyterCompile portal_component correctly catches exceptions as expected by the Jupyter frontend as also automatically abort the current transaction. Take the case in which one line in a statement is valid and another is not. """ portal = self.getPortalObject() script_id = "JupyterCompile_errorResult" script_container = portal.portal_skins.custom new_test_title = "Wendelin Test 1" # Check if the existing title is different from new_test_title or not if portal.getTitle()==new_test_title: new_test_title = "Wendelin" python_script = """ portal = context.getPortalObject() portal.setTitle('%s') print an_undefined_variable """%new_test_title # Create python_script object with the above given code and containers createZODBPythonScript(script_container, script_id, '', python_script) self.tic() # Call the above created script in jupyter_code jupyter_code = """ portal = context.getPortalObject() portal.%s() """%script_id # Make call to Base_runJupyter to run the jupyter code which is making # a call to the newly created ZODB python_script and assert if the call # processes correctly the NameError as we are sending an invalid # python_code to it. # result = portal.Base_runJupyter( jupyter_code=jupyter_code, old_notebook_context=portal.Base_createNotebookContext() ) self.assertEquals(result['ename'], 'NameError') self.assertEquals(result['result_string'], None) # There's no need to abort the current transaction. The error handling code # should be responsible for this, so we check the script's title script_title = script_container.JupyterCompile_errorResult.getTitle() self.assertNotEqual(script_title, new_test_title) removeZODBPythonScript(script_container, script_id) # Test that calling Base_runJupyter shouldn't change the context Title self.assertNotEqual(portal.getTitle(), new_test_title)
def _simulatePayzenEvent_processUpdate(self): script_name = 'PayzenEvent_processUpdate' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """portal_workflow = context.portal_workflow portal_workflow.doActionFor(context, action='edit_action', comment='Visited by PayzenEvent_processUpdate') """ ) self.commit()
def _simulateSoftwareInstance_tryToAllocatePartition(self): script_name = 'SoftwareInstance_tryToAllocatePartition' if script_name in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_name) createZODBPythonScript(self.portal.portal_skins.custom, script_name, '*args, **kwargs', '# Script body\n' """portal_workflow = context.portal_workflow portal_workflow.doActionFor(context, action='edit_action', comment='Visited by SoftwareInstance_tryToAllocatePartition') """ ) transaction.commit()
def decorated(self, *args, **kw): if script_id in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_id) createZODBPythonScript(self.portal.portal_skins.custom, script_id, params_string, code_string) try: result = f(self, *args, **kw) finally: if script_id in self.portal.portal_skins.custom.objectIds(): self.portal.portal_skins.custom.manage_delObjects(script_id) transaction.commit() return result
def stepMakeEntitySendEmailFailOnce(self, sequence=None): createZODBPythonScript( self.portal.portal_skins.custom, 'Entity_sendEmail', self.portal.Entity_sendEmail.params(), """portal = context.getPortalObject() for activity in portal.portal_activities.getMessageList(): if activity.method_id == script.id: if activity.retry == 0: raise ValueError('Failure on purpose') else: return context.skinSuper('custom', script.id)(%s)""" % (self.portal.Entity_sendEmail.params(), ))
def stepMakeEntitySendEmailFailOnce(self, sequence=None): createZODBPythonScript( self.portal.portal_skins.custom, 'Entity_sendEmail', self.portal.Entity_sendEmail.params(), """portal = context.getPortalObject() for activity in portal.portal_activities.getMessageList(): if activity.method_id == script.id: if activity.retry == 0: raise ValueError('Failure on purpose') else: return context.skinSuper('custom', script.id)(%s)""" % (self.portal.Entity_sendEmail.params(),) )
def decorated(self, *args, **kw): if script_id in self.portal.portal_skins.custom.objectIds(): raise ValueError('Precondition failed: %s exists in custom' % script_id) createZODBPythonScript(self.portal.portal_skins.custom, script_id, params_string, code_string) transaction.commit() try: result = f(self, *args, **kw) finally: if script_id in self.portal.portal_skins.custom.objectIds(): self.portal.portal_skins.custom.manage_delObjects(script_id) transaction.commit() return result
def stepCreateAsTextScript(self, sequence=None, **kw) : """ This script returns a different address format. """ createZODBPythonScript(self.getPortal().portal_skins.custom, 'Address_asText', '', """ return '%s\\n%s %s' % \\ (context.getStreetAddress(), context.getZipCode(), context.getCity()) """) # Flush the cache because _getTypeBasedMethod caches the result, # so that script will not be used. self.getPortal().portal_caches.clearCache(cache_factory_list=('erp5_content_long',))
def testBase_executeJupyterRespectPreference(self): self.login('dev_user') removeZODBPythonScript(self.getPortal().portal_skins.custom, "ERP5Site_isDataNotebookEnabled") createZODBPythonScript(self.getPortal().portal_skins.custom, "ERP5Site_isDataNotebookEnabled", '', "return False") self.tic() jupyter_code = "a = 1\na" reference = 'Test.Notebook.PreferenceHandle' result = self.portal.Base_executeJupyter( reference=reference, python_expression=jupyter_code ) self.assertEqual(result, 'The synchronous and unrestricted implementation is not enabled on the server')
def createAndRunScript(self, *args, **kwargs): # we do not care the script name for security test thus use uuid1 name = str(uuid.uuid1()) code = '\n'.join(args) expected = kwargs.get('expected', None) script_container = self.portal.portal_skins.custom try: createZODBPythonScript(script_container, name, '**kw', code) if expected: self.assertEqual(self.runScript(script_container, name), expected) else: self.runScript(script_container, name) finally: removeZODBPythonScript(script_container, name)
def testAlarmConfiguratorItem(self): """ Test Alarm Configurator Item """ configuration_save = self.createConfigurationSave() bc = configuration_save.getParentValue() property_map = { "active_sense_method_id": "Base_setDummy", "periodicity_hour_list": [5, 6], "periodicity_minute_list": [30, 31], "periodicity_minute_frequency": 5, "periodicity_month_list": [1, 2], "periodicity_month_day_list": [3, 4], "periodicity_week_list": [6, 7], } item = configuration_save.addConfigurationItem( "Alarm Configurator Item", id="my_test_alarm", title="My Test Alarm", **property_map) createZODBPythonScript(self.getPortal().portal_skins.custom, property_map["active_sense_method_id"], "", "context.setEnabled(0)") self.tic() item.fixConsistency() self.tic() alarm = getattr(self.portal.portal_alarms, "my_test_alarm", None) self.assertNotEquals(None, alarm) self.assertEqual(alarm.getEnabled(), True) self.assertEqual(alarm.getTitle(), "My Test Alarm") self.assertEqual(alarm.getPeriodicityMinuteFrequency(), property_map["periodicity_minute_frequency"]) self.assertEqual(alarm.getPeriodicityMonthList(), property_map["periodicity_month_list"]) self.assertEqual(alarm.getPeriodicityMonthDayList(), property_map["periodicity_month_day_list"]) self.assertEqual(alarm.getPeriodicityHourList(), property_map["periodicity_hour_list"]) self.assertEqual(alarm.getPeriodicityHourList(), property_map["periodicity_hour_list"]) self.assertEqual(alarm.getActiveSenseMethodId(), property_map["active_sense_method_id"]) self.assertNotEquals(alarm.getPeriodicityStartDate(), None) self.assertTrue(alarm.getPeriodicityStartDate() < DateTime()) alarm.activeSense() self.tic() self.assertEqual(alarm.getEnabled(), 0)
def createBasicScriptreturnJSONWithTimestamp( self, name="ERP5Site_returnJSONWithTimestamp", ): createZODBPythonScript( self.portal.portal_skins.custom, name, "text_data, form_reference", """ import json return json.dumps({ "datetime": DateTime().ISO8601(), "content": text_data, }, indent=2) """) return name
def afterSetUp(self): """Called after setup completed. """ self.portal = self.getPortal() # create a security configuration script skin_folder = self.portal.portal_skins.custom if 'ERP5Type_getSecurityCategoryMapping' not in skin_folder.objectIds( ): createZODBPythonScript( skin_folder, 'ERP5Type_getSecurityCategoryMapping', '', """return (( 'ERP5Type_getSecurityCategoryFromAssignment', context.getPortalObject().getPortalAssignmentBaseCategoryList() ),) """) # configure group, site, function categories category_tool = self.getCategoryTool() for bc in ['group', 'site', 'function']: base_cat = category_tool[bc] code = bc[0].upper() if base_cat.get('subcat', None) is not None: continue base_cat.newContent(portal_type='Category', id='subcat', codification="%s1" % code) # add another function subcategory. function_category = category_tool['function'] if function_category.get('another_subcat', None) is None: function_category.newContent(portal_type='Category', id='another_subcat', codification='F2') self.defined_category = "group/subcat\n"\ "site/subcat\n"\ "function/subcat" # any member can add organisations self.portal.organisation_module.manage_permission( 'Add portal content', roles=['Member', 'Manager'], acquire=1) self.username = '******' # create a user and open an assignement pers = self.getPersonModule().newContent(portal_type='Person', reference=self.username, password=self.username) assignment = pers.newContent(portal_type='Assignment', group='subcat', site='subcat', function='subcat') assignment.open() self.person = pers self.tic()
def stepSetPythonScriptForDeliveryBuilder(self, **kw): """ Make a script which returns existing Sale Invoice Transactions, so that all movements are merged into existing ones. """ delivery_select_method_id = 'Test_selectDelivery' createZODBPythonScript( self.portal.portal_skins.custom, delivery_select_method_id, 'movement_list=None', """ return context.getPortalObject().portal_catalog(portal_type='Sale Invoice Transaction') """) delivery_builder = getattr(self.portal.portal_deliveries, self.delivery_builder_id) delivery_builder.delivery_select_method_id = delivery_select_method_id
def test_03_customGenerateNewId(self): """ Test that id_generator property is honored. """ id_generator_script_name = 'testIdGenerator' id_generator_id_list = ['first_id', 'second_id'] createZODBPythonScript(self.getPortal().portal_skins.erp5_core, id_generator_script_name, '', 'return %s[len(context)]' % (repr(id_generator_id_list), )) self.folder.setIdGenerator(id_generator_script_name) self.assertEquals(self.folder.getIdGenerator(), id_generator_script_name) for expected_length in xrange(len(id_generator_id_list)): self.assertEquals(len(self.folder), expected_length) obj = self.newContent() self.assertEquals(obj.getId(), id_generator_id_list[expected_length])
def createUpdateScriptjIOWebSectionCreateOrganisationFromJSON(self): createZODBPythonScript( self.portal.portal_skins.custom, "jIOWebSection_createOrganisationFromJSON", "data, list_error", """ import json if not data["portal_type"] == "Organisation": raise ValueError(json.dumps({"organisation_creation": "Data doesn't match Organisation Creation"})) organisation = context.getPortalObject().organisation_module.newContent( portal_type="Organisation", title=data["title"], ) return json.dumps({ "id": organisation.getRelativeUrl() }, indent=2) """)