Commit 445e8fa8 authored by Jérome Perrin's avatar Jérome Perrin

ERP5TypeTestCase: rework default manager password generation

The default manager user (ERP5TypeTestCase) now have a random password
generated at the beginning of test. The password is stored as a class
attribute of the test case instance.
Many tests have been updated to not generate manager user and use the
existing one instead. When tests need to create users (for example
users in the root acl_users), we try to give them a random password and
to delete the users afterward.

For functional tests, the approach is that ERP5TypeFunctionalTestCase
sets cookies with manager username and password before running zelenium
tests, so that in case tests want to log in again as manager, they can
read the username and password from cookies.

Another significant changes is that we no longer have the same user in
ERP5/acl_users and /acl_users, some tests were logging in as the root
user in ways that never seemed intentional.

This also revealed (through test_manager_actions_on_portal from
testERP5Core) that some tests were running with a user without all the
expected permissions and the "Manager Components" actions was not
visible for the default manager user. Fixing this also revealed that
two actions ("Manage Components" and "Manage Callables") had the same
priority, so the later was modified to use a different priority.
parent 9964c13d
Pipeline #34940 failed with stage
in 0 seconds
......@@ -49,18 +49,6 @@ this selenium test is executed at first. so other tests are executed by anonymou
<td></td>
</tr>
<tr>
<td>openAndWait</td>
<td>${base_url}/ERP5Site_createSuperUser</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Done</td>
<td></td>
</tr>
<tr>
<td>openAndWait</td>
<td>${base_url}/Base_validateRule</td>
......
acl_users = context.getPortalObject().acl_users
if not acl_users.getUserById('super_user'):
acl_users.zodb_users.manage_addUser(
user_id='super_user',
login_name='super_user',
password='super_user',
confirm='super_user',
)
# BBB for PAS 1.9.0 we pass a response and undo the redirect
response = container.REQUEST.RESPONSE
acl_users.zodb_roles.manage_assignRoleToPrincipals(
'Manager',
('super_user',),
RESPONSE=response)
response.setStatus(200)
return 'Done'
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="_reconstructor" module="copy_reg"/>
</klass>
<tuple>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
<global name="object" module="__builtin__"/>
<none/>
</tuple>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>ERP5Site_createSuperUser</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
......@@ -13,10 +13,20 @@
<td></td>
</tr>
</tal:block>
<tr>
<td>storeEval</td>
<td>selenium.getCookieByName("manager_username")</td>
<td>manager_username</td>
</tr>
<tr>
<td>storeEval</td>
<td>selenium.getCookieByName("manager_password")</td>
<td>manager_password</td>
</tr>
<tal:block tal:define="submit_name python:'//input[@value=\'Login\']'">
<tal:block metal:use-macro="python: context.Zuite_CommonTemplate.macros['login']">
<tal:block metal:fill-slot="username">super_user</tal:block>
<tal:block metal:fill-slot="password">super_user</tal:block>
<tal:block metal:fill-slot="username">${manager_username}</tal:block>
<tal:block metal:fill-slot="password">${manager_password}</tal:block>
</tal:block>
</tal:block>
<tr>
......
......@@ -462,10 +462,7 @@ class TestAdvancedSaleInvoice(TestAdvancedInvoice):
portal = self.getPortal()
builder = portal.portal_deliveries.advanced_sale_invoice_transaction_builder
delivery_movement_group_list = builder.getDeliveryMovementGroupList()
uf = self.getPortal().acl_users
uf._doAddUser('admin', '', ['Manager'], [])
user = uf.getUserById('admin').__of__(uf)
newSecurityManager(None, user)
self.login()
for movement_group in delivery_movement_group_list:
if movement_group.getPortalType() == 'Property Movement Group':
# it contains 'start_date' and 'stop_date' only, so we remove
......@@ -476,6 +473,7 @@ class TestAdvancedSaleInvoice(TestAdvancedInvoice):
collect_order_group='delivery',
int_index=len(delivery_movement_group_list)+1
)
uf = portal.acl_users
user = uf.getUserById('test_user').__of__(uf)
newSecurityManager(None, user)
......
......@@ -43,10 +43,6 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
"""
Test for erp5_authentication_policy business template.
"""
manager_username = 'zope'
manager_password = 'zope'
credential = '%s:%s' % (manager_username, manager_password)
def getTitle(self):
return "TestAuthenticationPolicy"
......@@ -63,12 +59,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
'erp5_authentication_policy',)
def afterSetUp(self):
portal = self.getPortal()
uf = portal.acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
self.loginByUserName(self.manager_username)
portal = self.portal
kw = dict(portal_type='ERP5 Login',
reference='test')
if portal.portal_catalog.getResultValue(**kw) is None:
......
......@@ -43,10 +43,6 @@ class TestAuoLogout(ERP5TypeTestCase):
"""
Test for erp5_auto_logout business template.
"""
manager_username = 'zope'
manager_password = 'zope'
credential = '%s:%s' % (manager_username, manager_password)
def getTitle(self):
return "TestAuthenticationPolicy"
......@@ -60,10 +56,6 @@ class TestAuoLogout(ERP5TypeTestCase):
def afterSetUp(self):
portal = self.getPortal()
uf = portal.acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
self.loginByUserName(self.manager_username)
# setup short auto-logout period
portal.portal_preferences.default_site_preference.setPreferredMaxUserInactivityDuration(5)
portal.portal_preferences.default_site_preference.enable()
......
......@@ -26,12 +26,11 @@
#
##############################################################################
import unittest
import transaction
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import createZODBPythonScript
from AccessControl.SecurityManagement import newSecurityManager
TESTED_SKIN_FOLDER_ID = 'custom'
......@@ -57,12 +56,6 @@ class TestCachedSkinsTool(ERP5TypeTestCase):
# Use None as skinname to keep using the default one.
self.getSkinnableObject().changeSkin(skinname=None)
def login(self): # pylint:disable=arguments-differ
uf = self.portal.acl_users
uf._doAddUser('vincent', '', ['Manager'], [])
user = uf.getUserById('vincent').__of__(uf)
newSecurityManager(None, user)
def getSkinnableObject(self):
"""
Return the skinnable object (access to SkinsTool through cache).
......@@ -137,7 +130,7 @@ class TestCachedSkinsTool(ERP5TypeTestCase):
script_id = 'Base_getOwnerId'
ob = self.portal.portal_activities
orig = getattr(ob, script_id)()
self.assertEqual(orig, 'ERP5TypeTestCase')
self.assertEqual(orig, ob.getOwner().getId())
try:
script = createZODBPythonScript(tested_skin_folder, script_id, '',
'return not %r' % orig)
......@@ -149,6 +142,3 @@ class TestCachedSkinsTool(ERP5TypeTestCase):
self.assertRaises(AttributeError, getattr(ob, script_id))
finally:
self.abort()
if __name__ == '__main__':
unittest.main()
......@@ -4137,7 +4137,7 @@ VALUES
"""
ret = self.publish(
self.portal.portal_catalog.getPath(),
basic='ERP5TypeTestCase:')
basic='%s:%s' % (self.manager_username, self.manager_password))
self.assertEqual(httplib.OK, ret.getStatus())
# check if we did not just publish the result of `str(portal_catalog.__call__())`,
# but a proper page
......
......@@ -28,7 +28,6 @@
##############################################################################
import collections
import pprint
import httplib
import urlparse
import base64
......@@ -51,7 +50,6 @@ if 1: # BBB
import Acquisition
global_translation_service = None
from zope.i18n.interfaces import ITranslationDomain, \
IFallbackTranslationDomainFactory
@zope.interface.implementer(ITranslationDomain)
......@@ -107,18 +105,9 @@ class TestERP5Core(ERP5TypeTestCase, ZopeTestCase.Functional):
run_all_test = 1
quiet = 1
manager_username = 'rc'
manager_password = 'w'
def getTitle(self):
return "ERP5Core"
def login(self, quiet=0, run=run_all_test):
uf = self.getPortal().acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
user = uf.getUserById(self.manager_username).__of__(uf)
newSecurityManager(None, user)
def afterSetUp(self):
self.login()
self.portal_id = self.portal.getId()
......@@ -216,9 +205,8 @@ class TestERP5Core(ERP5TypeTestCase, ZopeTestCase.Functional):
for actions in actions_by_priority.values():
if len(actions) > 1:
self.assertFalse(actions) # no actions with same priority
msg = ("Actions do not match. Expected:\n%s\n\nGot:\n%s\n" %
(pprint.pformat(expected), pprint.pformat(got)))
self.assertEqual(expected, got, msg)
self.maxDiff = None
self.assertEqual(got, expected)
def test_manager_actions_on_portal(self):
# as manager:
......@@ -227,6 +215,8 @@ class TestERP5Core(ERP5TypeTestCase, ZopeTestCase.Functional):
'id': 'bt_tool'},
{'title': 'Configure Categories',
'id': 'category_tool'},
{'title': 'Manage Components',
'id': 'component_tool'},
{'title': 'Manage Callables',
'id': 'callable_tool'},
{'title': 'Configure Portal Types',
......@@ -534,8 +524,6 @@ class TestERP5Core(ERP5TypeTestCase, ZopeTestCase.Functional):
organisation = self.portal.organisation_module.newContent()
person = self.portal.person_module.newContent(
default_career_subordination_value=organisation)
for obj in person, organisation:
obj.manage_addLocalRoles(self.manager_username, ['Assignor'])
self.commit()
self.assertEqual(0, organisation.getRelationCountForDeletion())
self.tic()
......@@ -633,7 +621,6 @@ class TestERP5Core(ERP5TypeTestCase, ZopeTestCase.Functional):
# Login as the above user
newSecurityManager(None, user)
self.auth = '%s:%s' % (login_name, password)
self.commit()
self.tic()
_, api_netloc, _, _, _ = urlparse.urlsplit(self.portal.absolute_url())
......
......@@ -32,7 +32,6 @@
from __future__ import print_function
import unittest
from AccessControl.SecurityManagement import newSecurityManager
from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from DocumentTemplate.html_quote import html_quote
......@@ -48,18 +47,10 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional):
Please refer to the ERP5 developer howto for more explanation
http://www.erp5.org/HowToDisplayOrEditHTML
"""
manager_username = 'zope'
manager_password = 'zope'
def getTitle(self):
return "EditorField"
def login(self, *args, **kw):
uf = self.getPortal().acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager', ], [])
user = uf.getUserById(self.manager_username).__of__(uf)
newSecurityManager(None, user)
def getBusinessTemplateList(self):
"""
Return the list of required business templates.
......
......@@ -38,10 +38,6 @@ from erp5.component.test.testDms import makeFileUpload
class TestERP5Discussion(ERP5TypeTestCase):
"""Test for erp5_discussion business template.
"""
manager_username = 'manager'
manager_password = 'pwd'
def getTitle(self):
return "Test ERP5 Discussion"
......@@ -59,17 +55,6 @@ class TestERP5Discussion(ERP5TypeTestCase):
'erp5_jquery',
'erp5_discussion', )
def login(self, *args, **kw):
uf = self.getPortal().acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
user = uf.getUserById(self.manager_username).__of__(uf)
newSecurityManager(None, user)
def afterSetUp(self):
self.login()
self.portal_id = self.portal.getId()
self.auth = '%s:%s' % (self.manager_username, self.manager_password)
def beforeTearDown(self):
self.abort()
for module in (self.portal.discussion_thread_module,):
......
......@@ -48,15 +48,16 @@
import unittest
import time
import StringIO
import base64
from subprocess import Popen, PIPE
from unittest import expectedFailure
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import FileUpload
from Products.ERP5Type.tests.utils import DummyLocalizer
from Products.ERP5Type.Utils import bytes2str, str2bytes
from Products.ERP5OOo.OOoUtils import OOoBuilder
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl import getSecurityManager
from erp5.component.document.Document import NotConvertedError
from Products.ERP5Form.PreferenceTool import Priority
from Products.ERP5Type.tests.utils import createZODBPythonScript
......@@ -226,8 +227,8 @@ class TestDocument(TestDocumentMixin):
return (width, height)
def getURLSizeList(self, uri, **kw):
# __ac=RVJQNVR5cGVUZXN0Q2FzZTo%3D is encoded ERP5TypeTestCase with empty password
url = '%s?%s&__ac=%s' %(uri, make_query(kw), 'RVJQNVR5cGVUZXN0Q2FzZTo%3D')
kw['__ac'] = bytes2str(base64.b64encode(str2bytes('%s:%s' % (self.manager_username, self.manager_password))))
url = '%s?%s' % (uri, make_query(kw))
format_=kw.get('format', 'jpeg')
infile = urllib.urlopen(url)
# save as file with proper incl. format filename (for some reasons PIL uses this info)
......@@ -1186,7 +1187,7 @@ class TestDocument(TestDocumentMixin):
self.tic()
# login as another user
super(TestDocument, self).loginByUserName('user1')
self.loginByUserName('user1')
document_4 = portal.document_module.newContent(
portal_type = 'Presentation',
description = 'owner different user contributing document',
......@@ -1269,7 +1270,7 @@ class TestDocument(TestDocumentMixin):
self.assertSameSet([], getAdvancedSearchStringResultList(**kw))
# only my docs
super(TestDocument, self).loginByUserName('user1')
self.loginByUserName('user1')
kw = {'searchabletext_any': 'owner'}
# should return all documents matching a word no matter if we're owner or not
self.assertSameSet([web_page_1, document_4], getAdvancedSearchStringResultList(**kw))
......@@ -1705,7 +1706,7 @@ class TestDocument(TestDocumentMixin):
self.tic()
# login as first one
super(TestDocument, self).loginByUserName('contributor1')
self.loginByUserName('contributor1')
doc = document_module.newContent(portal_type='File',
title='Test1')
self.tic()
......@@ -1714,7 +1715,7 @@ class TestDocument(TestDocumentMixin):
doc.getContributorValueList())
# login as second one
super(TestDocument, self).loginByUserName('contributor2')
self.loginByUserName('contributor2')
doc.manage_setLocalRoles(person2.Person_getUserId(), ['Assignor',])
doc.edit(title='Test2')
self.tic()
......@@ -1971,8 +1972,7 @@ document.write('<sc'+'ript type="text/javascript" src="http://somosite.bg/utb.ph
response.getHeader('content-type')
assert response.getStatus() == httplib.OK
# assume there is no password
credential = '%s:' % (getSecurityManager().getUser().getId(),)
credential = '%s:%s' % (self.manager_username, self.manager_password)
tested_list = []
frame_list = range(pages_number)
# assume that ZServer is configured with 4 Threads
......@@ -2158,10 +2158,15 @@ return 1
Test extensible content of some DMS types. As this is possible only on URL traversal use publish.
"""
# Create a root level zope user
root_user_folder = self.getPortalObject().aq_parent.acl_users
if not root_user_folder.getUserById('zope_user'):
root_user_folder._doAddUser('zope_user', '', ['Manager',], [])
self.commit()
root_user_folder = self.app.acl_users
assert not root_user_folder.getUserById('zope_user')
zope_user_password = self.newPassword()
root_user_folder._doAddUser('zope_user', zope_user_password, ['Manager',], [])
def remove_user():
root_user_folder._doDelUsers(('zope_user', ))
self.tic()
self.addCleanup(remove_user)
# Create document with good content
document = self.portal.document_module.newContent(portal_type='Presentation')
upload_file = makeFileUpload('TEST-en-003.odp')
......@@ -2169,7 +2174,7 @@ return 1
self.tic()
self.assertEqual('converted', document.getExternalProcessingState())
for object_url in ('img1.html', 'img2.html', 'text1.html', 'text2.html'):
for credential in ['ERP5TypeTestCase:', 'zope_user:']:
for credential in ['%s:%s' % (self.manager_username, self.manager_password), 'zope_user:%s' % zope_user_password]:
response = self.publish('%s/%s' %(document.getPath(), object_url),
basic=credential)
self.assertIn('200 OK', response.getOutput())
......@@ -2372,8 +2377,8 @@ return 1
Return original content on traversal.
"""
def getURL(uri, **kw):
# __ac=RVJQNVR5cGVUZXN0Q2FzZTo%3D is encoded ERP5TypeTestCase with empty password
url = '%s?%s&__ac=%s' %(uri, urllib.urlencode(kw), 'RVJQNVR5cGVUZXN0Q2FzZTo%3D')
kw['__ac'] = bytes2str(base64.b64encode(str2bytes('%s:%s' % (self.manager_username, self.manager_password))))
url = '%s?%s' % (uri, make_query(kw))
return urllib.urlopen(url)
ooo_document = self.portal.document_module.newContent(portal_type='Presentation')
......@@ -2961,6 +2966,7 @@ return 1
[sub_document_value]
)
class TestDocumentWithSecurity(TestDocumentMixin):
username = 'yusei'
......@@ -2969,8 +2975,9 @@ class TestDocumentWithSecurity(TestDocumentMixin):
return "DMS with security"
def login(self, *args, **kw):
uf = self.getPortal().acl_users
uf._doAddUser(self.username, '', ['Auditor', 'Author'], [])
# login as a user with only Auditor / Author roles
uf = self.portal.acl_users
uf._doAddUser(self.username, self.newPassword(), ['Auditor', 'Author'], [])
user = uf.getUserById(self.username).__of__(uf)
newSecurityManager(None, user)
......@@ -3030,7 +3037,6 @@ class TestDocumentWithSecurity(TestDocumentMixin):
those properties are taken into account when the user
views an image
"""
super(TestDocumentWithSecurity, self).login('yusei')
preference_tool = self.portal.portal_preferences
#get the thumbnail sizes defined by default on default site preference
default_thumbnail_image_height = \
......
......@@ -39,10 +39,10 @@ from email.parser import Parser as EmailParser
import transaction
from AccessControl import Unauthorized
from AccessControl.SecurityManagement import newSecurityManager
from Testing import ZopeTestCase
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import FileUpload, createZODBPythonScript
from Products.ERP5Type.Utils import bytes2str, str2bytes
from erp5.component.document.Document import ConversionError
from PIL import Image
......@@ -117,19 +117,11 @@ class TestERP5WebWithDms(ERP5TypeTestCase, ZopeTestCase.Functional):
"""
run_all_test = 1
quiet = 0
manager_username = 'zope'
manager_password = 'zope'
website_id = 'test'
def getTitle(self):
return "ERP5WebWithDms"
def login(self, quiet=0, run=run_all_test):
uf = self.getPortal().acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
user = uf.getUserById(self.manager_username).__of__(uf)
newSecurityManager(None, user)
def getBusinessTemplateList(self):
"""
Return the list of required business templates.
......@@ -551,7 +543,7 @@ class TestERP5WebWithDms(ERP5TypeTestCase, ZopeTestCase.Functional):
reference=image_reference)
image.publish()
self.tic()
credential = 'ERP5TypeTestCase:'
credential = '%s:%s' % (self.manager_username, self.manager_password)
# testing TextDocument
response = self.publish(website.absolute_url_path() + '/' +\
web_page_reference, credential)
......@@ -705,8 +697,15 @@ return True
request = portal.REQUEST
request['PARENTS'] = [self.app]
self.getPortalObject().aq_parent.acl_users._doAddUser(
'zope_user', '', ['Manager',], [])
root_user_folder = self.app.acl_users
assert not root_user_folder.getUserById('zope_user')
zope_user_password = self.newPassword()
root_user_folder._doAddUser('zope_user', zope_user_password, ['Manager',], [])
def remove_user():
root_user_folder._doDelUsers(('zope_user', ))
self.tic()
self.addCleanup(remove_user)
website = self.setupWebSite()
web_section_portal_type = 'Web Section'
website.newContent(portal_type=web_section_portal_type)
......@@ -718,7 +717,10 @@ return True
reference=document_reference,
file=upload_file)
self.tic()
credential_list = ['ERP5TypeTestCase:', 'zope_user:']
credential_list = [
'%s:%s' % (self.manager_username, self.manager_password),
'zope_user:%s' % zope_user_password
]
for credential in credential_list:
# first, preview the draft in its physical location (in document module)
......@@ -813,7 +815,7 @@ return True
reference=image_reference)
image.publish()
self.tic()
credential = 'ERP5TypeTestCase:'
credential = '%s:%s' % (self.manager_username, self.manager_password)
# testing Image conversions, raw
......@@ -1749,7 +1751,10 @@ return True
)
published_page.publish()
self.tic()
auth_cookie = {'__ac': b64encode('ERP5TypeTestCase:')}
auth_cookie = {
'__ac': bytes2str(b64encode(str2bytes(
'%s:%s' % (self.manager_username, self.manager_password))))
}
# ERP5 portal, not through Caching Policy Manager
response = requests.get(
......
......@@ -54,9 +54,6 @@ def makeFileUpload(name, as_name=None):
class TestWebDavSupport(ERP5TypeTestCase):
"""Test for WEBDAV access.
"""
authentication = 'ERP5TypeTestCase:'
def getTitle(self):
return "Test WebDav Support"
......@@ -72,7 +69,7 @@ class TestWebDavSupport(ERP5TypeTestCase):
)
def afterSetUp(self):
pass
self.authentication = '%s:%s' % (self.manager_username, self.manager_password)
def clearModule(self, module):
module.manage_delObjects(list(module.objectIds()))
......
......@@ -35,10 +35,6 @@ class TestExternalAccount(ERP5TypeTestCase):
"""
Test for erp5_authentication_policy business template.
"""
manager_username = 'zope'
manager_password = 'zope'
credential = '%s:%s' % (manager_username, manager_password)
def getTitle(self):
return "TestExternalAccount"
......@@ -54,10 +50,6 @@ class TestExternalAccount(ERP5TypeTestCase):
def afterSetUp(self):
portal = self.getPortal()
uf = portal.acl_users
uf._doAddUser(self.manager_username, self.manager_password, ['Manager'], [])
self.loginByUserName(self.manager_username)
# Setup auth policy