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

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import unittest
from Products.ERP5Type.tests.utils import reindex
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import DummyMailHost
from Products.ERP5Type.tests.Sequence import SequenceList
import email, re
from email.Header import decode_header, make_header
from email.Utils import parseaddr
import transaction
import cgi
from urlparse import urlparse

use_verbose_security = 0
if use_verbose_security:
  import AccessControl
  AccessControl.Implementation.setImplementation('python')
  AccessControl.ImplPython.setDefaultBehaviors(
              ownerous=True,
              authenticated=True,
              verbose=True)

Gabriel Monnerat's avatar
Gabriel Monnerat committed
50

51 52 53 54 55 56 57
class TestERP5Credential(ERP5TypeTestCase):

  def getTitle(self):
    return "ERP5 Credential"

  def getBusinessTemplateList(self):
    return (
58
      'erp5_full_text_myisam_catalog',
59
      'erp5_core_proxy_field_legacy',
60
      'erp5_base',
61 62 63 64 65
      'erp5_jquery',
      'erp5_ingestion_mysql_innodb_catalog',
      'erp5_ingestion',
      'erp5_web',
      'erp5_crm',
66 67
      'erp5_credential',
      'erp5_administration')
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

  def afterSetUp(self):
    """Prepare the test."""
    self.createCategories()
    self.enableAlarm()
    self.validateNotificationMessages()
    # add a dummy mailhost not to send real messages
    if 'MailHost' in self.portal.objectIds():
      self.portal.manage_delObjects(['MailHost'])
    self.portal._setObject('MailHost', DummyMailHost('MailHost'))

  @reindex
  def enableAlarm(self):
    """activate the alarm"""
    portal = self.getPortalObject()
    alarm = portal.portal_alarms.accept_submitted_credentials
    if not alarm.isEnabled():
      alarm.setEnabled(True)

  def validateNotificationMessages(self):
    '''validate all notification messages'''
    portal = self.getPortalObject()
    notification_message_module = portal.getDefaultModule('Notification Message')
    for notification_message in notification_message_module.contentValues():
      if notification_message.getValidationState() == 'draft':
        notification_message.validate()

  @reindex
  def createCategories(self):
    """Create the categories for our test. """
    # create categories
Gabriel Monnerat's avatar
Gabriel Monnerat committed
99
    for cat_string in self.getNeededCategoryList():
100 101 102 103 104 105 106
      base_cat = cat_string.split("/")[0]
      # if base_cat not exist, create it
      if getattr(self.getPortal().portal_categories, base_cat, None) == None:
        self.getPortal().portal_categories.newContent(\
                                          portal_type='Base Category',
                                          id=base_cat)
      base_cat_value = self.getPortal().portal_categories[base_cat]
Gabriel Monnerat's avatar
Gabriel Monnerat committed
107 108
      for cat in cat_string.split("/")[1:]:
        if not cat in base_cat_value.objectIds():
109 110 111 112 113 114 115
          base_cat_value = base_cat_value.newContent(
                    portal_type='Category',
                    id=cat,
                    title=cat.replace('_', ' ').title(),)
        else:
          base_cat_value = base_cat_value[cat]
    # check categories have been created
Gabriel Monnerat's avatar
Gabriel Monnerat committed
116
    for cat_string in self.getNeededCategoryList():
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)

  def getNeededCategoryList(self):
    """return a list of categories that should be created."""
    return ('role/client/distributor',
            'role/internal',
            'role/media',
            'role/partner',
            'function/member',
            'function/manager',
            'function/agent',
            'site/dakar',
            'site/paris',
            'site/tokyo',
           )

  def beforeTearDown(self):
    self.login()
    transaction.abort()
    # clear modules if necessary
    module_list = (self.portal.getDefaultModule('Credential Request'),
        self.portal.getDefaultModule('Credential Update'),
        self.portal.getDefaultModule('Credential Recovery'),
        self.portal.getDefaultModule('Person'))
    for module in module_list:
      module.manage_delObjects(list(module.objectIds()))
145
    self.resetCredentialSystemPreference()
146 147 148 149
    transaction.commit()
    self.tic()
    self.logout()

150 151 152 153 154 155 156
  def resetCredentialSystemPreference(self):
    self.login()
    preference = self._getPreference()
    preference.edit(preferred_credential_request_automatic_approval=False,
                    preferred_credential_recovery_automatic_approval=False,
                    preferred_organisation_credential_update_automatic_approval=False,
                    preferred_person_credential_update_automatic_approval=False,
157
                    preferred_credential_alarm_automatic_call=False,
158 159
                    preferred_subscription_assignment_category_list=[],
                    preferred_credential_contract_document_reference=None)
160 161
    self._enablePreference()

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
  # Copied from bt5/erp5_egov/TestTemplateItem/testEGovMixin.py
  def decode_email(self, file):
    # Prepare result
    theMail = {
      'attachment_list': [],
      'body': '',
      # Place all the email header in the headers dictionary in theMail
      'headers': {}
    }
    # Get Message
    msg = email.message_from_string(file)
    # Back up original file
    theMail['__original__'] = file
    # Recode headers to UTF-8 if needed
    for key, value in msg.items():
      decoded_value_list = decode_header(value)
      unicode_value = make_header(decoded_value_list)
      new_value = unicode_value.__unicode__().encode('utf-8')
      theMail['headers'][key.lower()] = new_value
    # Filter mail addresses
    for header in ('resent-to', 'resent-from', 'resent-cc', 'resent-sender',
                   'to', 'from', 'cc', 'sender', 'reply-to'):
      header_field = theMail['headers'].get(header)
      if header_field:
          theMail['headers'][header] = parseaddr(header_field)[1]
    # Get attachments
    body_found = 0
    for part in msg.walk():
      content_type = part.get_content_type()
      file_name = part.get_filename()
      # multipart/* are just containers
      # XXX Check if data is None ?
      if content_type.startswith('multipart'):
        continue
      # message/rfc822 contains attached email message
      # next 'part' will be the message itself
      # so we ignore this one to avoid doubling
      elif content_type == 'message/rfc822':
        continue
      elif content_type in ("text/plain", "text/html"):
        charset = part.get_content_charset()
        payload = part.get_payload(decode=True)
        #LOG('CMFMailIn -> ',0,'charset: %s, payload: %s' % (charset,payload))
        if charset:
          payload = unicode(payload, charset).encode('utf-8')
        if body_found:
          # Keep the content type
          theMail['attachment_list'].append((file_name,
                                             content_type, payload))
        else:
          theMail['body'] = payload
          body_found = 1
      else:
        payload = part.get_payload(decode=True)
        # Keep the content type
        theMail['attachment_list'].append((file_name, content_type,
                                           payload))
    return theMail

  def _getPreference(self):
    portal_preferences = self.getPreferenceTool()
    preference = getattr(portal_preferences, 'test_site_preference', None)
    if preference is None:
      preference = portal_preferences.newContent(portal_type='System Preference',
                                title='Default Site Preference',
                                id='test_site_preference')
    return preference

  def _enablePreference(self):
    preference = self._getPreference()
    if preference.getPreferenceState() == 'disabled':
      preference.enable()

  def _disablePreference(self):
    preference = self._getPreference()
    if preference.getPreferenceState() in ('enable', 'global'):
      preference.disable()

240
  def stepSetCredentialRequestAutomaticApprovalPreferences(self, sequence=None):
241 242
    self.login()
    preference = self._getPreference()
243
    automatic_call = sequence.get("automatic_call", True)
Łukasz Nowak's avatar
Łukasz Nowak committed
244
    preference.edit(preferred_credential_request_automatic_approval=True,
245
                    preferred_credential_alarm_automatic_call=automatic_call)
246
    self._enablePreference()
247 248 249 250
    self.stepTic()
    self.logout()

  def stepSetCredentialAssignmentPropertyList(self, sequence={}):
251 252
    category_list = sequence.get("category_list",
        ["role/internal", "function/member"])
253 254
    self.login()
    preference = self._getPreference()
255
    preference.edit(preferred_subscription_assignment_category_list=category_list)
256 257
    self._enablePreference()
    self.stepTic()
258 259
    self.logout()

Gabriel Monnerat's avatar
Gabriel Monnerat committed
260 261
  def stepSetOrganisationCredentialUpdateAutomaticApprovalPreferences(self,
      sequence=None, sequence_list=None, **kw):
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    self.login()
    preference = self._getPreference()
    preference.edit(preferred_organisation_credential_update_automatic_approval=True)
    self._enablePreference()
    transaction.commit()
    self.tic()
    self.logout()

  def stepSetCredentialRecoveryAutomaticApprovalPreferences(self, sequence=None,
      sequence_list=None, **kw):
    self.login()
    preference = self._getPreference()
    preference.edit(preferred_credential_recovery_automatic_approval=True)
    self._enablePreference()
    transaction.commit()
    self.tic()
    self.logout()

  def stepSetPersonCredentialUpdateAutomaticApprovalPreferences(self, sequence=None,
      sequence_list=None, **kw):
    self.login()
    preference = self._getPreference()
    preference.edit(preferred_person_credential_update_automatic_approval=True)
    self._enablePreference()
    transaction.commit()
    self.tic()
    self.logout()

Gabriel Monnerat's avatar
Gabriel Monnerat committed
290 291 292 293 294
  def stepCheckAssignmentAfterActiveLogin(self, sequence):
    portal_catalog = self.portal.portal_catalog
    reference = sequence["reference"]
    assignment_function = sequence["assignment_function"]
    assignment_role = sequence["assignment_role"]
Gabriel Monnerat's avatar
Gabriel Monnerat committed
295 296
    credential_request = portal_catalog.getResultValue(
        portal_type="Credential Request", reference=reference)
Gabriel Monnerat's avatar
Gabriel Monnerat committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    mail_message = portal_catalog.getResultValue(portal_type="Mail Message",
                                                 follow_up=credential_request)
    self.stepTic()
    self.logout()
    self.portal.ERP5Site_activeLogin(mail_message.getReference())
    self.login("ERP5TypeTestCase")
    self.stepTic()
    person = portal_catalog.getResultValue(reference=reference,
                                           portal_type="Person")
    assignment_list = person.objectValues(portal_type="Assignment")
    self.assertEquals(len(assignment_list), 1)
    assignment = assignment_list[0]
    self.assertEquals(assignment.getFunction(), assignment_function)
    self.assertEquals(assignment.getRole(), assignment_role)

312 313 314 315 316 317 318 319 320 321 322 323 324
  def getUserFolder(self):
    """Returns the acl_users. """
    return self.getPortal().acl_users

  def _assertUserExists(self, login, password):
    """Checks that a user with login and password exists and can log in to the
    system.
    """
    from Products.PluggableAuthService.interfaces.plugins import\
                                                      IAuthenticationPlugin
    uf = self.getUserFolder()
    self.assertNotEquals(uf.getUserById(login, None), None)
    for plugin_name, plugin in uf._getOb('plugins').listPlugins(
Gabriel Monnerat's avatar
Gabriel Monnerat committed
325
                                IAuthenticationPlugin):
326
      if plugin.authenticateCredentials(
Gabriel Monnerat's avatar
Gabriel Monnerat committed
327
                  {'login': login, 'password': password}) is not None:
328 329 330 331 332 333 334 335 336 337 338 339 340
        break
    else:
      self.fail("No plugin could authenticate '%s' with password '%s'" %
              (login, password))

  def _assertUserDoesNotExists(self, login, password):
    """Checks that a user with login and password does not exists and cannot
    log in to the system.
    """
    from Products.PluggableAuthService.interfaces.plugins import\
                                                        IAuthenticationPlugin
    uf = self.getUserFolder()
    for plugin_name, plugin in uf._getOb('plugins').listPlugins(
Gabriel Monnerat's avatar
Gabriel Monnerat committed
341
                              IAuthenticationPlugin):
342
      if plugin.authenticateCredentials(
Gabriel Monnerat's avatar
Gabriel Monnerat committed
343
                {'login': login, 'password': password}) is not None:
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        self.fail(
           "Plugin %s should not have authenticated '%s' with password '%s'" %
           (plugin_name, login, password))

  def stepCreateSimpleSubscriptionRequest(self, sequence=None, sequence_list=None,
      **kw):
    '''
    Create a simple subscription request
    '''
    request = self.portal.REQUEST
    request['PARENTS'] = [self.app]
    form_url = self.portal.absolute_url_path() + '/ERP5Site_viewNewCredentialRequestDialog'

    # logout to be annonymous
    self.logout()
    # check annonymous can access subscription form
    self.assertTrue("Desired Login Name" in request.traverse(form_url)())
    # fill in and submit the subscription form
362
    credential_reference = 'homie'
363 364 365
    result = self.portal.ERP5Site_newCredentialRequest(\
        first_name='Homer',
        last_name='Simpson',
366
        reference=credential_reference,
367 368 369 370
        password='secret',
        default_email_text='homer.simpson@fox.com',
        role_list=['internal'],
        )
371
    portal_status_message = sequence.get("portal_status_message",
Łukasz Nowak's avatar
Łukasz Nowak committed
372
        "Thanks%20for%20your%20registration.%20You%20will%20be%20receive%20an%20email%20to%20activate%20your%20account.")
373
    self.assertTrue('portal_status_message=%s' % portal_status_message in result, result)
374 375 376 377 378 379

    credential_request_module = self.portal.getDefaultModule('Credential Request')
    result = credential_request_module.contentValues(\
        portal_type='Credential Request', first_name='Homer',
        last_name='Simpson', reference='homie')
    self.assertEquals(len(result), 1)
380 381
    sequence.edit(subscription_request=result[0],
        person_reference=credential_reference)
382 383 384 385 386 387 388 389

  def stepAcceptSubscriptionRequest(self, sequence=None, sequence_list=None,
      **kw):
    self.login()
    subscription_request = sequence.get('subscription_request')
    subscription_request.accept()
    self.logout()

390 391 392 393 394 395 396
  def stepSubmitSubscriptionRequest(self, sequence=None, sequence_list=None,
      **kw):
    self.login()
    subscription_request = sequence.get('subscription_request')
    subscription_request.submit()
    self.logout()

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  def stepCheckAccountIsCreated(self, sequence=None, sequence_list=None, **kw):
    # check a person have been created
    person_module = self.portal.getDefaultModule('Person')
    person_result = person_module.contentValues(reference='homie')
    self.assertEquals(len(person_result), 1)
    person = person_result[0].getObject()
    self.assertEquals(person.getTitle(), 'Homer Simpson')
    self.assertEquals(person.getDefaultEmailText(), 'homer.simpson@fox.com')

    # check homie can log in the system
    self._assertUserExists('homie', 'secret')
    self.login('homie')
    from AccessControl import getSecurityManager
    self.assertEquals(str(getSecurityManager().getUser()), 'homie')

  def stepCreateCredentialUpdate(self, sequence=None, sequence_list=None, **kw):
    '''
    Create a credential update object an fill it with some modified
    informations
    '''
    self.login()
    # get the 'homie' person object
    person_module = self.portal.getDefaultModule('Person')
    result = person_module.searchFolder(reference='homie')
    self.assertEquals(len(result), 1)
    homie = result[0]

    # create a credential update
    credential_update_module = self.portal.getDefaultModule(\
        'Credential Update')
    credential_update = credential_update_module.newContent(\
        first_name='Homie',
        last_name='Simpsons', # add a 's' to the end of the last_name
        password='new_password',
        default_email_text='homie.simpsons@fox.com',
        destination_decision=homie.getRelativeUrl())

    credential_update.submit()
    self.assertEquals(credential_update.getValidationState(), 'submitted')
    sequence.edit(credential_update=credential_update)

  def stepAcceptCredentialUpdate(self, sequence=None, sequence_list=None,
      **kw):
    credential_update = sequence.get('credential_update')
    credential_update.accept()

  def stepCheckCredentialUpdate(self, sequence=None, sequence_list=None,
      **kw):
    self.login()
    # check the user with the updated password exists
    self._assertUserExists('homie', 'new_password')
    # check the user with the old password don't exists anymore
    self._assertUserDoesNotExists('homie', 'secret')

    # check that informations on the person object have been updated
    person_module = self.portal.getDefaultModule('Person')
    related_person_result = person_module.searchFolder(reference='homie')
    self.assertEquals(len(related_person_result), 1)
    related_person = related_person_result[0]
    self.assertEquals(related_person.getLastName(), 'Simpsons')
    self.assertEquals(related_person.getDefaultEmailText(),
    'homie.simpsons@fox.com')

  def stepCreateSubscriptionRequestWithSecurityQuestionCategory(self, sequence=None,
      sequence_list=None, **kw):
    request = self.portal.REQUEST
    request['PARENTS'] = [self.app]

    # fill in and submit the subscription form
466
    result = self._createCredentialRequest(\
467 468 469 470 471 472 473 474
        first_name='Homer',
        last_name='Simpson',
        reference='homie',
        password='secret',
        default_email_text='homer.simpson@fox.com',
        default_credential_question_question='credential/library_card_number',
        default_credential_question_answer='923R4293'
        )
475
    self.assertTrue('portal_status_message=Thanks%20for%20your%20registration.%20You%20will%20be%20receive%20an%20email%20to%20activate%20your%20account.'\
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        in result)

    transaction.commit()
    self.tic()
    credential_request_module = self.portal.getDefaultModule('Credential Request')
    result = credential_request_module.contentValues(\
        portal_type='Credential Request', first_name='Homer',
        last_name='Simpson', reference='homie')
    self.assertEquals(len(result), 1)
    sequence.edit(subscription_request=result[0])

  def stepCheckSecurityQuestionCategoryAsBeenCopiedOnPersonObject(self, sequence=None,
      sequence_list=None, **kw):
    person_module = self.portal.getDefaultModule('Person')
    related_person_result = person_module.contentValues(reference='homie')
    self.assertEquals(len(related_person_result), 1)
    related_person = related_person_result[0]
    self.assertEquals(related_person.getDefaultCredentialQuestionQuestion(),
        'credential/library_card_number')
    self.assertEquals(related_person.getDefaultCredentialQuestionAnswer(),
        '923R4293')

  def stepCreateSubscriptionRequestWithSecurityQuestionFreeText(self, sequence=None,
      sequence_list=None, **kw):
    request = self.portal.REQUEST
    request['PARENTS'] = [self.app]

    # logout to be annonymous
    self.logout()
    # fill in and submit the subscription form
    result = self.portal.ERP5Site_newCredentialRequest(\
        first_name='Homer',
        last_name='Simpson',
        reference='homie',
        password='secret',
        default_email_text='homer.simpson@fox.com',
        default_credential_question_question_free_text='Which '\
            'car model do you have ?',
        default_credential_question_answer='Renault 4L'
        )
516
    self.assertTrue('portal_status_message=Thanks%20for%20your%20registration.%20You%20will%20be%20receive%20an%20email%20to%20activate%20your%20account.'\
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        in result)

    transaction.commit()
    self.tic()
    credential_request_module = self.portal.getDefaultModule('Credential Request')
    result = credential_request_module.contentValues(\
        portal_type='Credential Request', first_name='Homer',
        last_name='Simpson', reference='homie')
    self.assertEquals(len(result), 1)
    sequence.edit(subscription_request=result[0])

  def stepCheckSecurityQuestionFreeTextAsBeenCopiedOnPersonObject(self, sequence=None,
      sequence_list=None, **kw):
    person_module = self.portal.getDefaultModule('Person')
    related_person_result = person_module.contentValues(reference='homie')
    self.assertEquals(len(related_person_result), 1)
    related_person = related_person_result[0]
    self.assertEquals(related_person.getDefaultCredentialQuestionQuestionFreeText(),
        'Which car model do you have ?')
    self.assertEquals(related_person.getDefaultCredentialQuestionAnswer(),
        'Renault 4L')

539
  def stepCreatePerson(self, sequence=None, sequence_list=None,
540
      **kw):
541 542 543
    """
      Create a simple person
    """
544 545 546 547
    portal = self.getPortalObject()
    # create a person with 'secret' as password
    self.login()
    person_module = portal.getDefaultModule('Person')
548
    person = person_module.newContent(title='Barney',
549 550 551 552
                             reference='barney',
                             password='secret',
                             default_email_text='barney@duff.com')
    # create an assignment
553
    assignment = person.newContent(portal_type='Assignment',
554 555
                      function='member')
    assignment.open()
556
    sequence.edit(person_reference=person.getReference())
557 558 559 560 561 562 563 564 565 566 567

  def stepCreateCredentialRecovery(self, sequence=None, sequence_list=None,
      **kw):
    '''
    Create a simple subscription request
    '''
    portal = self.getPortalObject()
    person_reference = sequence["person_reference"]
    person = portal.portal_catalog.getResultValue(portal_type="Person",
        reference=person_reference)
    sequence.edit(barney=person)
568 569 570 571 572 573 574 575 576 577 578 579 580
    # check barney can log in the system
    self._assertUserExists('barney', 'secret')
    self.login('barney')
    from AccessControl import getSecurityManager
    self.assertEquals(str(getSecurityManager().getUser()), 'barney')

    self.login()
    # create a credential recovery
    credential_recovery_module = portal.getDefaultModule('Credential Recovery')
    credential_recovery = credential_recovery_module.newContent(portal_type=\
        'Credential Recovery')

    # associate it with barney
581
    credential_recovery.setDestinationDecisionValue(person)
582 583
    sequence.edit(credential_recovery=credential_recovery)

584 585 586 587 588
  def stepRequestCredentialRecoveryWithERP5Site_newCredentialRecovery(self,
      sequence=None, sequence_list=None, **kw):
    person_reference = sequence["person_reference"]
    self.portal.ERP5Site_newCredentialRecovery(reference=person_reference)

589 590
  def stepLoginAsCurrentPersonReference(self, sequence=None,
      sequence_list=None, **kw):
591 592
    person_reference = sequence["person_reference"]
    self.login(person_reference)
593 594 595 596 597 598

  def stepCreateCredentialUpdateWithERP5Site_newCredentialUpdate(self,
      sequence=None, sequence_list=None, **kw):
    self.portal.ERP5Site_newPersonCredentialUpdate(first_name="tom",
        default_email_text="tom@host.com")

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
  def stepCreateCredentialRecoveryWithSensitiveAnswer(self, sequence=None,
      sequence_list=None, **kw):
    person_reference = sequence["person_reference"]
    result = self.portal.ERP5Site_newCredentialRecovery(
        reference=person_reference,
        default_credential_question_question='credential/library_card_number',
        default_credential_question_answer='ABCDeF',
        )
    message_str = "You%20didn%27t%20enter%20the%20correct%20answer."
    self.assertTrue(message_str not in result)
    self.stepTic()
    self.login()
    result_list = self.portal.portal_catalog(
        portal_type='Credential Recovery', reference=person_reference)
    self.assertEquals(1, len(result_list))
    credential_recovery = result_list[0]
    sequence.edit(credential_recovery=credential_recovery)

617 618 619 620 621 622 623
  def stepSelectCredentialUpdate(self, sequence=None, sequence_list=None,
      **kw):
    self.login()
    credential_update = self.portal.portal_catalog.getResultValue(
        portal_type="Credential Update")
    sequence["credential_update"] = credential_update

624 625 626 627 628 629 630 631 632 633
  def stepCheckCredentialRecoveryCreation(self, sequence=None, 
      sequence_list=None, **kw):
    person_reference = sequence["person_reference"]
    result_list = self.portal.portal_catalog(
        portal_type='Credential Recovery', reference=person_reference)
    self.assertEquals(1, len(result_list))
    credential_recovery = result_list[0]
    person = credential_recovery.getDestinationDecisionValue()
    self.assertEquals("Barney", person.getTitle())
    self.assertEquals("barney@duff.com", person.getEmailText())
634
    sequence["credential_recovery"] = credential_recovery
635

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  def stepSubmitCredentialRecovery(self, sequence=None, sequence_list=None,
      **kw):
    credential_recovery = sequence.get('credential_recovery')
    credential_recovery.submit()

  def stepAcceptCredentialRecovery(self, sequence=None, sequence_list=None,
      **kw):
    credential_recovery = sequence.get('credential_recovery')
    credential_recovery.accept()

  def stepCheckEmailIsSent(self, sequence=None, sequence_list=None, **kw):
    '''
      Check an email containing the password reset link as been sent
    '''
    barney = sequence.get('barney')
651 652 653 654
    if not barney:
      reference = sequence.get('person_reference')
      barney = self.portal.portal_catalog.getResultValue(portal_type="Person",
          reference=reference)
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

    # after accept, an email is send containing the reset link
    last_message = self.portal.MailHost._last_message
    rawstr = r"""PasswordTool_viewResetPassword"""
    decoded_message = self.decode_email(last_message[2])
    body_message = decoded_message['body']
    match_obj = re.search(rawstr, body_message)

    # check the reset password link is in the mail
    self.assertNotEquals(match_obj, None)

    # check the mail is sent to the requester :
    send_to = decoded_message['headers']['to']
    self.assertEqual(barney.getDefaultEmailText(), send_to)

  def stepCheckPasswordChange(self, sequence=None, sequence_list=None, **kw):
    '''
      check it's possible to change the user password using the link in the
      email
    '''
    # get the url
    last_message = self.portal.MailHost._last_message
    rawstr = r"""PasswordTool_viewResetPassword"""
    decoded_message = self.decode_email(last_message[2])
    body_message = decoded_message['body']
    match_obj = re.search(rawstr, body_message)
    # check the reset password link is in the mail
    self.assertNotEquals(match_obj, None)
    url = None
    for line in body_message.splitlines():
      match_obj = re.search(rawstr, line)
      if match_obj is not None:
        url = line[line.find('http:'):]
688
    url = url.strip()
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    self.assertNotEquals(url, None)
    response = self.publish(url)
    parameters = cgi.parse_qs(urlparse(url)[4])
    self.assertTrue('reset_key' in parameters)
    key = parameters['reset_key'][0]
    # before changing, check that the user exists with 'secret' password
    self._assertUserExists('barney', 'secret')
    self.portal.portal_password.changeUserPassword(user_login="barney",
                                                   password="new_password",
                                                   password_confirmation="new_password",
                                                   password_key=key)
    transaction.commit()
    self.tic()
    # reset the cache
    self.portal.portal_caches.clearAllCache()
    # check we cannot login anymore with the previous password 'secret'
    self._assertUserDoesNotExists('barney', 'secret')

    # check we can now login with the new password 'new_password'
    self._assertUserExists('barney', 'new_password')

710 711 712 713 714 715
  def _createCredentialRequest(self, first_name="Barney",
                               last_name="Simpson",
                               reference="barney",
                               password="secret",
                               default_email_text="barney@duff.com",
                               **kw):
716
    self.logout()
717
    result = self.portal.ERP5Site_newCredentialRequest(first_name=first_name,
718 719 720 721 722 723 724 725
        last_name=last_name,
        reference=reference,
        password=password,
        career_subordination_title="",
        default_email_text=default_email_text,
        default_telephone_text="223344",
        default_address_street_address="Test Street",
        default_address_city="Campos",
726 727
        default_address_zip_code="28024030",
        **kw)
728 729
    self.login("ERP5TypeTestCase")
    self.stepTic()
730
    return result
731 732 733 734 735 736

  def stepCreateCredentialRequestSample(self, sequence=None,
      sequence_list=None, **kw):
    credential_reference = "credential_reference"
    self._createCredentialRequest(reference=credential_reference)
    sequence.edit(credential_reference=credential_reference)
Gabriel Monnerat's avatar
Gabriel Monnerat committed
737

738 739 740 741 742 743 744 745 746
  def stepCheckIfMailMessageWasPosted(self, sequence=None,
      sequence_list=None, **kw):
    credential_reference_str = sequence["credential_reference"]
    portal_catalog = self.portal.portal_catalog
    credential_reference = portal_catalog.getResultValue(
        portal_type="Credential Request", reference=credential_reference_str)
    mail_message = portal_catalog.getResultValue(portal_type="Mail Message",
                                                 follow_up=credential_reference)
    self.assertEquals(mail_message.getSimulationState(), "started")
Gabriel Monnerat's avatar
Gabriel Monnerat committed
747
    self.assertTrue("key=%s" % mail_message.getReference() in mail_message.getTextContent())
748 749 750 751 752 753 754 755 756 757

  def stepSetPreferredCredentialAlarmAutomaticCallAsFalse(self, sequence):
    sequence.edit(automatic_call=False)

  def stepSetAssigneeRoleToCurrentPersonInCredentialUpdateModule(self,
      sequence=None, sequence_list=None, **kw):
    person_reference = sequence["person_reference"]
    self.portal.credential_update_module.manage_setLocalRoles(person_reference,
        ['Assignor',])

758 759 760 761 762 763 764 765 766
  def stepSetAssigneeRoleToCurrentPersonInCredentialRecoveryModule(self,
      sequence=None, sequence_list=None, **kw):
    person_reference = sequence["person_reference"]
    self.portal.credential_recovery_module.manage_setLocalRoles(person_reference,
        ['Assignor',])

  def stepLogin(self, sequence):
    self.login()

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
  def stepSetAuditorRoleToCurrentPerson(self, sequence=None,
      sequence_list=None, **kw):
    person_reference = sequence["person_reference"]
    self.login()
    person = self.portal.portal_catalog.getResultValue(portal_type="Person",
        reference=person_reference)
    person.manage_setLocalRoles(person_reference, ["Auditor"])
    self.logout()

  def stepCheckPersonAfterUpdatePerson(self, sequence=None,
      sequence_list=None, **kw):
    person = self.portal.portal_catalog.getResultValue(
      reference=sequence["person_reference"], portal_type="Person")
    self.assertEquals("tom", person.getFirstName())
    self.assertEquals("Simpson", person.getLastName())
    self.assertEquals("tom@host.com", person.getDefaultEmailText())

784 785 786 787 788 789
  def stepCheckPersonWhenCredentialUpdateFail(self, sequence=None,
      sequence_list=None, **kw):
    person = self.portal.portal_catalog.getResultValue(
      reference=sequence["person_reference"], portal_type="Person")
    self.assertEquals("Barney", person.getFirstName())

790
  def test_01_simpleSubscriptionRequest(self):
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
    '''
    Check that is possible to subscribe to erp5
    '''
    sequence_list = SequenceList()
    sequence_string = 'CreateSimpleSubscriptionRequest Tic '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_02_acceptSubscriptionRequest(self):
    '''
    Check that after approval, the account is created and the user is able to
    log in the system.
    '''
    sequence_list = SequenceList()
Łukasz Nowak's avatar
Łukasz Nowak committed
806 807
    sequence_string = 'SetCredentialAssignmentPropertyList '\
                      'CreateSimpleSubscriptionRequest Tic '\
Łukasz Nowak's avatar
Łukasz Nowak committed
808
                      'SubmitSubscriptionRequest Tic '\
809 810 811 812 813 814 815 816
                      'AcceptSubscriptionRequest Tic '\
                      'CheckAccountIsCreated Tic '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_03_simpleCredentialUpdate(self):
    '''
817
    Check it's possible to update credential informations using credential
818 819 820
    update
    '''
    sequence_list = SequenceList()
Łukasz Nowak's avatar
Łukasz Nowak committed
821 822
    sequence_string = 'SetCredentialAssignmentPropertyList ' \
                      'CreateSimpleSubscriptionRequest '\
Łukasz Nowak's avatar
Łukasz Nowak committed
823
                      'SubmitSubscriptionRequest Tic '\
824 825 826 827 828 829 830 831
                      'AcceptSubscriptionRequest Tic '\
                      'CreateCredentialUpdate '\
                      'AcceptCredentialUpdate Tic '\
                      'CheckCredentialUpdate '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

832 833 834
  def stepSetCredentialRequestCreatedMessage(self, sequence=None, **kw):
    sequence['portal_status_message'] = 'Credential%20Request%20Created'

835 836
  def test_04_automaticCredentialRequestApproval(self):
    '''
837 838
    if the property preferred_credential_request_automatic_approval is True on
    System Preference object. it means that the Credential Request object
839
    should be accepted automatically and account created without any human
840 841
    intervention.
    Check that the user is create without human intervention
842 843 844
    '''
    sequence_list = SequenceList()
    sequence_string = 'SetCredentialRequestAutomaticApprovalPreferences '\
845 846
                      'SetCredentialAssignmentPropertyList '\
                      'SetCredentialRequestCreatedMessage '\
847 848 849 850 851 852 853 854
                      'CreateSimpleSubscriptionRequest Tic '\
                      'CheckAccountIsCreated '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_05_automaticCredentialUpdateApproval(self):
    '''
Łukasz Nowak's avatar
Łukasz Nowak committed
855
    if the property preferred_credential_update_automatic_approval is True on
856 857 858 859
    System Preference object. it means that the Credential Update object
    should be accepted automatically and account created without any human
    intervention.
    Check that the user is create without human intervention
860 861 862
    '''
    sequence_list = SequenceList()
    sequence_string = 'SetPersonCredentialUpdateAutomaticApprovalPreferences '\
Łukasz Nowak's avatar
Łukasz Nowak committed
863
                      'SetCredentialAssignmentPropertyList '\
864
                      'CreateSimpleSubscriptionRequest '\
Łukasz Nowak's avatar
Łukasz Nowak committed
865
                      'SubmitSubscriptionRequest Tic '\
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
                      'AcceptSubscriptionRequest Tic '\
                      'CheckAccountIsCreated '\
                      'CreateCredentialUpdate Tic '\
                      'CheckCredentialUpdate '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_06_checkSecurityQuestionCategoryDefinition(self):
    '''
    Check that its possible to define a security question selecting a category
    or by entering free text.
    '''
    sequence_list = SequenceList()
    sequence_string = 'CreateSubscriptionRequestWithSecurityQuestionCategory '\
881
                      'SubmitSubscriptionRequest Tic '\
882 883 884 885 886 887 888 889 890 891 892 893 894
                      'AcceptSubscriptionRequest Tic '\
                      'CheckSecurityQuestionCategoryAsBeenCopiedOnPersonObject '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_07_checkSecurityQuestionFreeTextDefinition(self):
    '''
    Check that its possible to define a security question selecting a category
    or by entering free text.
    '''
    sequence_list = SequenceList()
    sequence_string = 'CreateSubscriptionRequestWithSecurityQuestionFreeText '\
895
                      'SubmitSubscriptionRequest Tic '\
896 897 898 899 900 901 902 903 904 905 906 907
                      'AcceptSubscriptionRequest Tic '\
                      'CheckSecurityQuestionFreeTextAsBeenCopiedOnPersonObject '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_08_passwordRecovery(self):
    '''
    check that a user that forget his password is able to set a new one and
    log in the system with this new password
    '''
    sequence_list = SequenceList()
908 909
    sequence_string = 'CreatePerson Tic '\
                      'CreateCredentialRecovery Tic '\
910 911 912 913 914 915 916 917
                      'SubmitCredentialRecovery Tic '\
                      'AcceptCredentialRecovery Tic '\
                      'CheckEmailIsSent Tic '\
                      'CheckPasswordChange Tic '\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

918 919 920
  def testMailMessagePosted(self):
    """ Test if the Mail Message was posted correctly """
    sequence_list = SequenceList()
Gabriel Monnerat's avatar
Gabriel Monnerat committed
921 922
    sequence_string = 'SetPreferredCredentialAlarmAutomaticCallAsFalse '\
                      'SetCredentialRequestAutomaticApprovalPreferences '\
923
                      'CreateCredentialRequestSample '\
924
                      'CheckIfMailMessageWasPosted '\
925

926 927 928
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

929
  def testMailFromMailMessageEvent(self):
Gabriel Monnerat's avatar
Gabriel Monnerat committed
930 931 932 933
    """
      Check that the email is created correctly after create on Credentail
      Request with user's information
    """
934 935
    sequence = dict(automatic_call=False)
    self.stepSetCredentialRequestAutomaticApprovalPreferences(sequence)
936 937 938 939
    self._createCredentialRequest(first_name="Vifib", 
                                 last_name="Test",
                                 reference="vifibtest")
    portal_catalog = self.portal.portal_catalog
940 941 942 943 944
    credential_request = portal_catalog.getResultValue(
        portal_type="Credential Request", reference="vifibtest", 
        first_name="Vifib", last_name="Test")
    mail_message = portal_catalog.getResultValue(
        portal_type="Mail Message", follow_up=credential_request)
945 946 947 948
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, message_text = last_message
    self.assertEquals(mfrom, 'Portal Administrator <postmaster@localhost>')
949
    self.assertEquals(['Vifib Test <barney@duff.com>'], mto)
950 951
    self.assertNotEquals(re.search("Subject\:.*Welcome", message_text), None)
    self.assertNotEquals(re.search("Hello\ Vifib\ Test\,", message_text), None)
952 953
    self.assertNotEquals(re.search("key\=..%s" % mail_message.getReference(),
      message_text), None)
954

955 956 957 958 959
  def testAssignmentCreationUsingSystemPreferenceProperty(self):
    """
      Check that the category list are used correctly to create a new
      assignment
    """
960 961 962 963
    sequence = dict(automatic_call=False)
    self.stepSetCredentialRequestAutomaticApprovalPreferences(sequence)
    self.stepSetCredentialAssignmentPropertyList()
    self._createCredentialRequest()
964
    sequence = dict(reference="barney",
965 966 967 968 969 970 971 972 973 974 975 976
                   assignment_function="member",
                   assignment_role="internal")
    self.stepCheckAssignmentAfterActiveLogin(sequence)
    category_list = ["role/client", "function/agent"]
    self.stepSetCredentialAssignmentPropertyList(
        dict(category_list=category_list))
    self._createCredentialRequest(reference="credential_user")
    sequence = dict(reference="credential_user",
                   assignment_function="agent",
                   assignment_role="client")
    self.stepCheckAssignmentAfterActiveLogin(sequence)

977
  def testERP5Site_activeLogin(self):
978 979 980 981
    """
      Test if the script WebSection_activeLogin will create one user
    correctly
    """
982 983
    sequence = dict(automatic_call=False)
    self.stepSetCredentialRequestAutomaticApprovalPreferences(sequence)
984 985
    self.stepSetCredentialAssignmentPropertyList()
    self.stepTic()
986 987
    self._createCredentialRequest()
    portal_catalog = self.portal.portal_catalog
988
    credential_request = portal_catalog.getResultValue(
989
        portal_type="Credential Request", reference="barney")
990 991 992 993 994 995
    mail_message = portal_catalog.getResultValue(portal_type="Mail Message",
                                                 follow_up=credential_request)
    self.logout()
    self.portal.ERP5Site_activeLogin(mail_message.getReference())
    self.login("ERP5TypeTestCase")
    self.stepTic()
996
    person = portal_catalog.getResultValue(reference="barney",
997
        portal_type="Person")
998 999 1000 1001 1002
    assignment_list = person.objectValues(portal_type="Assignment")
    self.assertNotEquals(assignment_list, [])
    self.assertEquals(len(assignment_list), 1)
    assignment = assignment_list[0]
    self.assertEquals(assignment.getValidationState(), "open")
1003 1004
    self.assertEquals(person.getValidationState(), "validated")

1005
  def testERP5Site_newCredentialRequest(self):
1006 1007 1008 1009
    """
      Check that the script ERP5Site_newCredentialRequest will create one
      Credential Request correctly
    """
1010 1011
    sequence = dict(automatic_call=False)
    self.stepSetCredentialRequestAutomaticApprovalPreferences(sequence)
1012
    self.stepSetCredentialAssignmentPropertyList()
1013 1014
    self._createCredentialRequest()
    portal_catalog = self.portal.portal_catalog
1015
    credential_request = portal_catalog.getResultValue(
1016 1017
        portal_type="Credential Request", reference="barney")
    self.assertEquals(credential_request.getFirstName(), "Barney")
1018
    self.assertEquals(credential_request.getDefaultEmailText(),
1019
        "barney@duff.com")
1020 1021
    self.assertEquals(credential_request.getRole(), "internal")
    self.assertEquals(credential_request.getFunction(), "member")
1022

1023
  def test_double_ERP5Site_newCredentialRequest(self):
1024 1025
    """Check that ERP5Site_newCredentialRequest will not create conflicting
       credentials."""
1026
    sequence = dict(automatic_call=True)
1027 1028
    self.stepSetCredentialRequestAutomaticApprovalPreferences(sequence)
    self.stepSetCredentialAssignmentPropertyList()
Łukasz Nowak's avatar
Łukasz Nowak committed
1029 1030
    response = self._createCredentialRequest()
    self.assertTrue('Credential%20Request%20Created.' in response)
1031 1032 1033 1034 1035 1036 1037 1038 1039
    portal_catalog = self.portal.portal_catalog
    credential_request = portal_catalog.getResultValue(
        portal_type="Credential Request", reference="barney")
    self.assertEquals(credential_request.getFirstName(), "Barney")
    self.assertEquals(credential_request.getDefaultEmailText(),
        "barney@duff.com")
    self.assertEquals(credential_request.getRole(), "internal")
    self.assertEquals(credential_request.getFunction(), "member")

Łukasz Nowak's avatar
Łukasz Nowak committed
1040
    self.portal.portal_alarms.accept_submitted_credentials.activeSense()
1041 1042
    transaction.commit()
    self.tic()
Łukasz Nowak's avatar
Łukasz Nowak committed
1043
    self.assertEqual('accepted', credential_request.getValidationState())
1044

Łukasz Nowak's avatar
Łukasz Nowak committed
1045 1046 1047
    response = self._createCredentialRequest()
    self.assertTrue('Selected%20login%20is%20already%20in%20use%2C%20pl'
      'ease%20choose%20different%20one' in  response)
1048

Łukasz Nowak's avatar
Łukasz Nowak committed
1049
    self.portal.portal_alarms.accept_submitted_credentials.activeSense()
1050 1051 1052
    transaction.commit()
    self.tic()

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
  def test_double_ERP5Site_newCredentialRequest_indexation(self):
    """Check that ERP5Site_newCredentialRequest will react correctly in case
       if indexation is still ongoing."""
    sequence = dict(automatic_call=True)
    self.stepSetCredentialRequestAutomaticApprovalPreferences(sequence)
    self.stepSetCredentialAssignmentPropertyList()
    reference = self.id()
    self.logout()
    response = self.portal.ERP5Site_newCredentialRequest(reference=reference,
        default_email_text='some@one.com',)
    self.login()
    self.assertTrue('Credential%20Request%20Created.' in response)
    transaction.commit()
    self.logout()
    response = self.portal.ERP5Site_newCredentialRequest(reference=reference,
        default_email_text='some@one.com',)
    self.login()
    # Now is time to assert that even if no reindexation was done yet, another
    # request will already refuse to create new credential request.
    self.assertTrue('Selected%20login%20is%20already%20in%20use%2C%20pl'
      'ease%20choose%20different%20one' in response)
    transaction.commit()
    self.tic()
    # just to be sure that last response not resulted with creation of object
    self.assertEqual(1, self.portal.portal_catalog.countResults(
      portal_type='Credential Request', reference=reference)[0][0])
1079

1080 1081
  def testERP5Site_newCredentialRecoveryWithNoSecurityQuestion(self):
    """
1082 1083
      Check that password recovery works when security question and answer are
      None
1084 1085 1086 1087
    """
    sequence_list = SequenceList()
    sequence_string = "CreatePerson Tic " \
           "RequestCredentialRecoveryWithERP5Site_newCredentialRecovery Tic " \
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
           "CheckCredentialRecoveryCreation " \
           "AcceptCredentialRecovery Tic "\
           "CheckEmailIsSent Tic "\
           "CheckPasswordChange "\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def testERP5Site_newCredentialUpdateWithNoSecurityQuestion(self):
    """
1098 1099 1100
      Check that the script ERP5Site_newCredentialUpdate creates correctly one
      Credential Update object is create correctly and the user is updated with
      new properties
1101 1102
    """
    sequence_list = SequenceList()
1103
    sequence_string = "CreateSimpleSubscriptionRequest Tic " \
Łukasz Nowak's avatar
Łukasz Nowak committed
1104
           "SubmitSubscriptionRequest Tic " \
1105 1106 1107 1108 1109 1110 1111 1112 1113
           "AcceptSubscriptionRequest Tic " \
           "SetAuditorRoleToCurrentPerson " \
           "SetAssigneeRoleToCurrentPersonInCredentialUpdateModule Tic " \
           "LoginAsCurrentPersonReference " \
           "CreateCredentialUpdateWithERP5Site_newCredentialUpdate Tic " \
           "SelectCredentialUpdate " \
           "AcceptCredentialUpdate Tic "\
           "CheckPersonAfterUpdatePerson "\

1114 1115 1116
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  def test_no_reset_assignment_ERP5Site_newCredentialUpdate(self):
    """Checks that assignments are left intact after credential update"""
    reference = self.id()
    person = self.portal.person_module.newContent(portal_type='Person',
      reference=reference,
      password='secret',
      role='internal')
    assignment = person.newContent(portal_type='Assignment', function='manager')
    assignment.open()
    transaction.commit()
    credential_update = self.portal.credential_update_module.newContent(
        portal_type='Credential Update',
        first_name='Some Name',
        destination_decision_value=person
      )
    credential_update.submit()
    credential_update.accept()
    self.tic()

    self.assertEqual('Some Name', person.getFirstName())
    self.assertEqual('manager', assignment.getFunction())

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  def stepCreatePersonWithQuestionUsingCamelCase(self, sequence):
    person_module = self.portal.getDefaultModule('Person')
    person = person_module.newContent(title='Barney',
                             reference='barney',
                             password='secret',
                             default_email_text='barney@duff.com')
    # create an assignment
    assignment = person.newContent(portal_type='Assignment',
                      function='member')
    assignment.open()
    sequence.edit(person_reference=person.getReference())

Łukasz Nowak's avatar
Łukasz Nowak committed
1151
  def test_checkCredentialQuestionIsNotCaseSensitive(self):
1152
    '''
1153
      Check that if the user enter an answer with a different case, this will still
1154 1155
    enought to reset his passord
    '''
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    sequence_list = SequenceList()
    sequence_string = "CreatePersonWithQuestionUsingCamelCase Tic " \
        "LoginAsCurrentPersonReference " \
        "CreateCredentialRecoveryWithSensitiveAnswer Tic " \
        "AcceptCredentialRecovery Tic " \
        "CheckEmailIsSent Tic "\
        "CheckPasswordChange Tic "\

    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)
1166

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
  def _prepareContractAndPreference(self):
    self.contract_reference = self.id()
    self.contract_content = 'My contract %s.' % self.contract_reference
    preference = self._getPreference()
    preference.edit(
      preferred_credential_contract_document_reference=self.contract_reference)
    self._enablePreference()
    # reset the cache in order to have this preference working
    self.portal.portal_caches.clearAllCache()
    
    self.contract = self.portal.web_page_module.newContent(
      portal_type='Web Page',
      reference=self.contract_reference,
      language='en',
      version='1',
      text_content=self.contract_content
    )
    self.contract.publish()
    transaction.commit()
    self.tic()

  def test_ERP5Site_viewCredentialRequestForm_contract(self):
    """Check that if contract document is configured and it is published it
       is shown while using join form"""
    self._prepareContractAndPreference()
    # render the form anonymous...
    self.logout()
    result = self.portal.ERP5Site_viewCredentialRequestForm()
    # but check as superuser
    self.login()
    self.assertTrue('%s/asStrippedHTML' % self.contract.getRelativeUrl() in result)

    # check if really contract has been correctly rendered
    self.logout()
    rendered = self.contract.asStrippedHTML()
    self.assertTrue(self.contract_content in rendered)

  def test_ERP5Site_viewCredentialRequestForm_contract_web(self):
    """Check that if contract document is configured and it is published it
       is shown while using join form in Web site"""
    self._prepareContractAndPreference()

    # create cool web site
    web_site = self.portal.web_site_module.newContent(portal_type='Web Site')
    web_site.publish()
    transaction.commit()
    self.tic()

    # render the form anonymous...
    self.logout()
    result = web_site.ERP5Site_viewCredentialRequestForm()
    # but check as superuser
    self.login()
    self.assertTrue(self.contract_reference in result)

    # check if really contract has been correctly rendered
    self.logout()
    rendered = self.portal.unrestrictedTraverse('%s/%s' % (
        web_site.getRelativeUrl(), self.contract_reference)).getTextContent()
    self.assertTrue(self.contract_content in rendered)
Gabriel Monnerat's avatar
Gabriel Monnerat committed
1227

1228 1229 1230 1231 1232 1233 1234 1235
  def test_ERP5Site_viewCredentialRequestForm_no_contract(self):
    """Check that if no contract is configured none is shown nor it is not
       required to accept it"""
    self.logout()
    result = self.portal.ERP5Site_viewCredentialRequestForm()
    self.assertFalse('Contract' in result)
    self.assertFalse('your_term_confirmation' in result)

1236 1237 1238 1239
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Credential))
  return suite