testCRM.py 50.5 KB
Newer Older
1
# -*- coding: utf-8 -*-
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 28 29 30
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#
# 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.
#
##############################################################################

import unittest
import os
31
import email.Header
32

33 34
import transaction

35
from Products.CMFCore.WorkflowCore import WorkflowException
36
from Products.ERP5Type.tests.utils import DummyMailHost
37
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
Yusei Tahara's avatar
Yusei Tahara committed
38 39 40 41
from Products.ERP5OOo.tests.testIngestion import conversion_server_host
from Products.ERP5OOo.tests.testIngestion import FILE_NAME_REGULAR_EXPRESSION
from Products.ERP5OOo.tests.testIngestion import REFERENCE_REGULAR_EXPRESSION

42 43 44 45 46 47 48
TEST_HOME = os.path.dirname(__file__)

def openTestFile(filename):
  return file(os.path.join(TEST_HOME, 'test_data', 'crm_emails', filename))


class TestCRM(ERP5TypeTestCase):
49 50 51
  def getTitle(self):
    return "CRM"

52
  def getBusinessTemplateList(self):
53 54
    return ('erp5_base',
            'erp5_crm',)
55

56
  def test_Event_CreateRelatedEvent(self):
57
    # test workflow to create a related event from responded event
58
    event_module = self.portal.event_module
59
    portal_workflow = self.portal.portal_workflow
60
    ticket = self.portal.campaign_module.newContent(portal_type='Campaign',)
61 62
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
63 64
      event = event_module.newContent(portal_type=ptype,
                                      follow_up_value=ticket)
65 66 67 68 69 70

      event.receive()
      event.respond()

      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)

71
      transaction.commit()
72 73 74 75 76 77 78
      self.tic()

      portal_workflow.doActionFor(event, 'create_related_event_action',
                                  related_event_portal_type=ptype,
                                  related_event_title='New Title',
                                  related_event_description='New Desc')

79
      transaction.commit()
80 81 82 83 84 85 86 87 88
      self.tic()

      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)

      related_event = event.getCausalityRelatedValue()

      self.assertEqual(related_event.getPortalType(), ptype)
      self.assertEqual(related_event.getTitle(), 'New Title')
      self.assertEqual(related_event.getDescription(), 'New Desc')
89
      self.assertEqual(related_event.getFollowUpValue(), ticket)
90
 
91
  def test_Event_CreateRelatedEventUnauthorized(self):
92
    # test that we don't get Unauthorized error when invoking the "Create
93 94
    # Related Event" without add permission on the module,
    # but will get WorkflowException error.
95 96
    event = self.portal.event_module.newContent(portal_type='Letter')
    self.portal.event_module.manage_permission('Add portal content', [], 0)
97 98 99 100 101
    self.assertRaises(WorkflowException,
                      event.Event_createRelatedEvent,
                      portal_type='Letter',
                      title='New Title',
                      description='New Desc')
102
    
103 104
  def test_Ticket_CreateRelatedEvent(self):
    # test action to create a related event from a ticket
105
    event_module_url = self.portal.event_module.absolute_url()
106
    ticket = self.portal.meeting_module.newContent(portal_type='Meeting')
107 108
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
109 110 111 112 113
      # incoming
      redirect = ticket.Ticket_newEvent(direction='incoming',
                                        portal_type=ptype,
                                        title='New Title',
                                        description='New Desc')
114 115
      self.assert_(redirect.startswith(event_module_url), redirect)
      new_id = redirect[len(event_module_url)+1:].split('/', 1)[0]
116 117 118 119 120 121 122 123 124
      new_event = self.portal.event_module._getOb(new_id)
      self.assertEquals(ticket, new_event.getFollowUpValue())
      self.assertEquals('new', new_event.getSimulationState())

      # outgoing
      redirect = ticket.Ticket_newEvent(direction='outgoing',
                                        portal_type=ptype,
                                        title='New Title',
                                        description='New Desc')
125 126
      self.assert_(redirect.startswith(event_module_url), redirect)
      new_id = redirect[len(event_module_url)+1:].split('/', 1)[0]
127 128 129
      new_event = self.portal.event_module._getOb(new_id)
      self.assertEquals(ticket, new_event.getFollowUpValue())
      self.assertEquals('planned', new_event.getSimulationState())
130

131 132 133 134 135 136 137 138 139 140
  def test_Ticket_CreateRelatedEventUnauthorized(self):
    # test that we don't get Unauthorized error when invoking the "Create
    # New Event" without add permission on the module
    ticket = self.portal.meeting_module.newContent(portal_type='Meeting')
    self.portal.event_module.manage_permission('Add portal content', [], 0)
    ticket.Ticket_newEvent(portal_type='Letter',
                           title='New Title',
                           description='New Desc',
                           direction='incoming')
   
141
  def test_PersonModule_CreateRelatedEventSelectionParams(self):
142
    # create related event from selected persons.
143 144 145 146 147 148 149 150 151
    person_module = self.portal.person_module
    pers1 = person_module.newContent(portal_type='Person', title='Pers1')
    pers2 = person_module.newContent(portal_type='Person', title='Pers2')
    pers3 = person_module.newContent(portal_type='Person', title='Pers3')
    self.portal.person_module.view()
    self.portal.portal_selections.setSelectionCheckedUidsFor(
                          'person_module_selection', [])
    self.portal.portal_selections.setSelectionParamsFor(
                          'person_module_selection', dict(title='Pers1'))
152
    transaction.commit()
153 154 155 156 157 158 159 160 161
    self.tic()
    person_module.PersonModule_newEvent(portal_type='Mail Message',
                                        title='The Event Title',
                                        description='The Event Descr.',
                                        direction='outgoing',
                                        selection_name='person_module_selection',
                                        follow_up='',
                                        text_content='Event Content',
                                        form_id='PersonModule_viewPersonList')
162

163
    transaction.commit()
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    self.tic()

    related_event = pers1.getDestinationRelatedValue(
                          portal_type='Mail Message')
    self.assertNotEquals(None, related_event)
    self.assertEquals('The Event Title', related_event.getTitle())
    self.assertEquals('The Event Descr.', related_event.getDescription())
    self.assertEquals('Event Content', related_event.getTextContent())

    for person in (pers2, pers3):
      self.assertEquals(None, person.getDestinationRelatedValue(
                                       portal_type='Mail Message'))

  def test_PersonModule_CreateRelatedEventCheckedUid(self):
    # create related event from selected persons.
    person_module = self.portal.person_module
    pers1 = person_module.newContent(portal_type='Person', title='Pers1')
    pers2 = person_module.newContent(portal_type='Person', title='Pers2')
    pers3 = person_module.newContent(portal_type='Person', title='Pers3')
    self.portal.person_module.view()
    self.portal.portal_selections.setSelectionCheckedUidsFor(
          'person_module_selection',
          [pers1.getUid(), pers2.getUid()])
187
    transaction.commit()
188 189 190 191 192 193 194 195 196 197
    self.tic()
    person_module.PersonModule_newEvent(portal_type='Mail Message',
                                        title='The Event Title',
                                        description='The Event Descr.',
                                        direction='outgoing',
                                        selection_name='person_module_selection',
                                        follow_up='',
                                        text_content='Event Content',
                                        form_id='PersonModule_viewPersonList')

198
    transaction.commit()
199 200 201 202 203 204 205 206 207 208 209 210 211
    self.tic()

    for person in (pers1, pers2):
      related_event = person.getDestinationRelatedValue(
                            portal_type='Mail Message')
      self.assertNotEquals(None, related_event)
      self.assertEquals('The Event Title', related_event.getTitle())
      self.assertEquals('The Event Descr.', related_event.getDescription())
      self.assertEquals('Event Content', related_event.getTextContent())

    self.assertEquals(None, pers3.getDestinationRelatedValue(
                                portal_type='Mail Message'))

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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  def test_SaleOpportunitySold(self):
    # test the workflow of sale opportunities, when the sale opportunity is
    # finaly sold
    so = self.portal.sale_opportunity_module.newContent(
                              portal_type='Sale Opportunity')
    self.assertEquals('draft', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'submit_action')
    self.assertEquals('submitted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'validate_action')
    self.assertEquals('contacted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'enquire_action')
    self.assertEquals('enquired', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'offer_action')
    self.assertEquals('offered', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'sell_action')
    self.assertEquals('sold', so.getSimulationState())

  def test_SaleOpportunityRejected(self):
    # test the workflow of sale opportunities, when the sale opportunity is
    # finaly rejected.
    # Uses different transitions than test_SaleOpportunitySold
    so = self.portal.sale_opportunity_module.newContent(
                              portal_type='Sale Opportunity')
    self.assertEquals('draft', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'validate_action')
    self.assertEquals('contacted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'enquire_action')
    self.assertEquals('enquired', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'offer_action')
    self.assertEquals('offered', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'reject_action')
    self.assertEquals('rejected', so.getSimulationState())

  def test_SaleOpportunityExpired(self):
    # test the workflow of sale opportunities, when the sale opportunity
    # expires
    so = self.portal.sale_opportunity_module.newContent(
                              portal_type='Sale Opportunity')
    self.assertEquals('draft', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'validate_action')
    self.assertEquals('contacted', so.getSimulationState())
    self.portal.portal_workflow.doActionFor(so, 'expire_action')
    self.assertEquals('expired', so.getSimulationState())

256 257 258
  def test_Event_AcknowledgeAndCreateEvent(self):
    """
    Make sure that when acknowledge event, we can create a new event.
259 260 261 262 263 264 265

    XXX This is probably meaningless in near future. event_workflow
    will be reviewed in order to have steps closer to usual packing 
    list workflow. For now we have a conflict name between the 
    acknowledge method of event_workflow and Acknowledgement features
    that comes with AcknowledgementTool. So for now disable site
    message in this test.
266 267 268
    """
    portal_workflow = self.portal.portal_workflow

269
    event_type_list = [x for x in self.portal.getPortalEventTypeList() \
270
                       if x not in  ['Site Message', 'Acknowledgement']]
271

272
    # if create_event option is false, it does not create a new event.
273
    for portal_type in event_type_list:
274 275 276 277 278
      ticket = self.portal.meeting_module.newContent(portal_type='Meeting',
                                                     title='Meeting1')
      ticket_url = ticket.getRelativeUrl()
      event = self.portal.event_module.newContent(portal_type=portal_type,
                                                  follow_up=ticket_url)
279
      transaction.commit()
280 281 282 283
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=0)
284
      transaction.commit()
285 286 287 288
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      
    # if create_event option is true, it create a new event.
289
    for portal_type in event_type_list:
290 291 292 293 294
      ticket = self.portal.meeting_module.newContent(portal_type='Meeting',
                                                     title='Meeting1')
      ticket_url = ticket.getRelativeUrl()
      event = self.portal.event_module.newContent(portal_type=portal_type,
                                                  follow_up=ticket_url)
295
      transaction.commit()
296 297 298 299
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action', create_event=1)
300
      transaction.commit()
301 302 303 304 305
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)

306 307
    # if quote_original_message option is true, the new event content will be
    # the current event message quoted.
308
    for portal_type in event_type_list:
309 310 311 312 313 314 315 316
      ticket = self.portal.meeting_module.newContent(portal_type='Meeting',
                                                     title='Meeting1')
      ticket_url = ticket.getRelativeUrl()
      event = self.portal.event_module.newContent(portal_type=portal_type,
                                                  follow_up=ticket_url,
                                                  title='Event Title',
                                                  text_content='Event Content',
                                                  text_format='text/plain')
317
      transaction.commit()
318 319 320 321 322 323
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 0)
      event.receive()
      portal_workflow.doActionFor(event, 'acknowledge_action',
                                  create_event=1,
                                  quote_original_message=1)
324
      transaction.commit()
325 326 327 328 329 330 331 332
      self.tic()
      self.assertEqual(len(event.getCausalityRelatedValueList()), 1)
      new_event = event.getCausalityRelatedValue()
      self.assertEqual(new_event.getFollowUp(), ticket_url)
      self.assertEqual(new_event.getTextFormat(), 'text/plain')
      self.assertEqual(new_event.getTextContent(), '> Event Content')
      self.assertEqual(new_event.getTitle(), 'Re: Event Title')

333 334

class TestCRMMailIngestion(ERP5TypeTestCase):
Yusei Tahara's avatar
Yusei Tahara committed
335
  """Test Mail Ingestion for standalone CRM.
336
  """
337 338
  def getTitle(self):
    return "CRM Mail Ingestion"
339 340

  def getBusinessTemplateList(self):
341 342 343
    # Mail Ingestion must work with CRM alone.
    return ('erp5_base',
            'erp5_ingestion',
Yusei Tahara's avatar
Yusei Tahara committed
344 345
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
346
            )
347 348 349

  def afterSetUp(self):
    portal = self.portal
350

351 352
    # create customer organisation and person
    if 'customer' not in portal.organisation_module.objectIds():
353
      portal.organisation_module.newContent(
354 355 356
              id='customer',
              portal_type='Organisation',
              title='Customer')
357 358
    customer_organisation = portal.organisation_module.customer
    if 'sender' not in portal.person_module.contentIds():
359 360 361 362 363
      portal.person_module.newContent(
              id='sender',
              title='Sender',
              subordination_value=customer_organisation,
              default_email_text='sender@customer.com')
364
    # also create the recipients
365
    if 'me' not in portal.person_module.contentIds():
366 367 368 369
      portal.person_module.newContent(
              id='me',
              title='Me',
              default_email_text='me@erp5.org')
370 371 372 373 374
    if 'he' not in portal.person_module.contentIds():
      portal.person_module.newContent(
              id='he',
              title='He',
              default_email_text='he@erp5.org')
375

376
    # make sure customers are available to catalog
377
    transaction.commit()
378
    self.tic()
379 380

  def beforeTearDown(self):
381
    transaction.abort()
382
    # clear modules if necessary
383 384
    for module in (self.portal.event_module,
                   self.portal.campaign_module):
385
      module.manage_delObjects(list(module.objectIds()))
386
    transaction.commit()
387 388
    self.tic()

Yusei Tahara's avatar
Yusei Tahara committed
389 390 391 392 393 394
  def _readTestData(self, filename):
    """read test data from data directory."""
    return file(os.path.join(os.path.dirname(__file__),
                             'test_data', 'crm_emails', filename)).read()

  def _ingestMail(self, filename=None, data=None):
395
    """ingest an email from the mail in data dir named `filename`"""
Yusei Tahara's avatar
Yusei Tahara committed
396 397
    if data is None:
      data=self._readTestData(filename)
398 399 400 401 402 403 404
    return self.portal.portal_contributions.newContent(
                    container_path='event_module',
                    file_name='postfix_mail.eml',
                    data=data)

  def test_findTypeByName_MailMessage(self):
    # without this, ingestion will not work
405 406 407 408 409
    self.assertEquals(
      'Mail Message',
      self.portal.portal_contribution_registry.findPortalTypeName(
      file_name='postfix_mail.eml', mime_type='message/rfc822', data='Test'
      ))
410 411 412 413 414 415 416 417 418 419

  def test_document_creation(self):
    # CRM email ingestion creates a Mail Message in event_module
    event = self._ingestMail('simple')
    self.assertEquals(len(self.portal.event_module), 1)
    self.assertEquals(event, self.portal.event_module.contentValues()[0])
    self.assertEquals('Mail Message', event.getPortalType())
    self.assertEquals('message/rfc822', event.getContentType())
  
  def test_title(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
420
    # title is found automatically, based on the Subject: header in the mail
421 422
    event = self._ingestMail('simple')
    self.assertEquals('Simple Mail Test', event.getTitle())
423
    self.assertEquals('Simple Mail Test', event.getTitleOrId())
424 425 426 427 428 429

  def test_asText(self):
    # asText requires portal_transforms
    event = self._ingestMail('simple')
    self.assertEquals('Hello,\nContent of the mail.\n', str(event.asText()))
 
430 431 432 433
  def test_sender(self):
    # source is found automatically, based on the From: header in the mail
    event = self._ingestMail('simple')
    # metadata discovery is done in an activity
434
    transaction.commit()
435 436 437 438 439 440
    self.tic()
    self.assertEquals('person_module/sender', event.getSource())

  def test_recipient(self):
    # destination is found automatically, based on the To: header in the mail
    event = self._ingestMail('simple')
441
    transaction.commit()
442
    self.tic()
443 444 445 446
    destination_list = event.getDestinationList()
    destination_list.sort()
    self.assertEquals(['person_module/he', 'person_module/me'],
                      destination_list)
447 448 449 450 451 452 453

  def test_follow_up(self):
    # follow up is found automatically, based on the content of the mail, and
    # what you defined in preference regexpr.
    # But, we don't want it to associate with the first campaign simply
    # because we searched against nothing
    self.portal.campaign_module.newContent(portal_type='Campaign')
454
    transaction.commit()
455 456
    self.tic()
    event = self._ingestMail('simple')
457
    transaction.commit()
458 459
    self.tic()
    self.assertEquals(None, event.getFollowUp())
Yusei Tahara's avatar
Yusei Tahara committed
460 461 462 463 464 465 466 467 468

  def test_portal_type_determination(self):
    """
    Make sure that ingested email will be correctly converted to
    appropriate portal type by email metadata.
    """
    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'Visit:Company A')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
469
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
470 471 472 473 474 475
    self.assertEqual(document.portal_type, 'Visit')
    self.assertEqual(document.getTitle(), 'Company A')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'Fax:Company B')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
476
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
477 478 479 480 481 482
    self.assertEqual(document.portal_type, 'Fax Message')
    self.assertEqual(document.getTitle(), 'Company B')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'TEST:Company B')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
483
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
484 485 486 487 488 489
    self.assertEqual(document.portal_type, 'Mail Message')
    self.assertEqual(document.getTitle(), 'TEST:Company B')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'visit:Company A')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
490
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
491 492 493 494 495 496
    self.assertEqual(document.portal_type, 'Visit')
    self.assertEqual(document.getTitle(), 'Company A')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'phone:Company B')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
497
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
498 499 500 501 502 503
    self.assertEqual(document.portal_type, 'Phone Call')
    self.assertEqual(document.getTitle(), 'Company B')

    message = email.message_from_string(self._readTestData('simple'))
    message.replace_header('subject', 'LETTER:Company C')
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
504
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
505 506 507 508 509 510 511
    self.assertEqual(document.portal_type, 'Letter')
    self.assertEqual(document.getTitle(), 'Company C')

    message = email.message_from_string(self._readTestData('simple'))
    body = message.get_payload()
    message.set_payload('Visit:%s' % body)
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
512
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
513 514 515 516 517 518 519
    self.assertEqual(document.portal_type, 'Visit')
    self.assertEqual(document.getTextContent(), body)

    message = email.message_from_string(self._readTestData('simple'))
    body = message.get_payload()
    message.set_payload('PHONE CALL:%s' % body)
    data = message.as_string()
Yusei Tahara's avatar
Yusei Tahara committed
520
    document = self._ingestMail(data=data)
Yusei Tahara's avatar
Yusei Tahara committed
521 522 523
    self.assertEqual(document.portal_type, 'Phone Call')
    self.assertEqual(document.getTextContent(), body)

Yusei Tahara's avatar
Yusei Tahara committed
524 525 526 527 528 529 530 531
  def test_forwarder_mail(self):
    """
    Make sure that if ingested email is forwarded one, the sender of
    original mail should be the sender of event and the sender of
    forwarded mail should be the recipient of event.
    """
    document = self._ingestMail(filename='forwarded')

532
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
533 534 535 536 537 538
    self.tic()

    self.assertEqual(document.getContentInformation().get('From'), 'Me <me@erp5.org>')
    self.assertEqual(document.getContentInformation().get('To'), 'crm@erp5.org')
    self.assertEqual(document.getSourceValue().getTitle(), 'Sender')
    self.assertEqual(document.getDestinationValue().getTitle(), 'Me')
539 540 541 542 543 544 545 546 547

  def test_forwarder_mail_with_attachment(self):
    """
    Make sure that if ingested email is forwarded one, the sender of
    original mail should be the sender of event and the sender of
    forwarded mail should be the recipient of event.
    """
    document = self._ingestMail(filename='forwarded_attached')

548
    transaction.commit()
549 550 551 552 553 554
    self.tic()

    self.assertEqual(document.getContentInformation().get('From'), 'Me <me@erp5.org>')
    self.assertEqual(document.getContentInformation().get('To'), 'crm@erp5.org')
    self.assertEqual(document.getSourceValue().getTitle(), 'Sender')
    self.assertEqual(document.getDestinationValue().getTitle(), 'Me')
Yusei Tahara's avatar
Yusei Tahara committed
555

556 557 558
  def test_encoding(self):
    document = self._ingestMail(filename='encoded')

559
    transaction.commit()
560 561 562 563 564 565 566 567 568 569 570
    self.tic()

    self.assertEqual(document.getContentInformation().get('To'),
                     'Me <me@erp5.org>')
    self.assertEqual(document.getSourceValue().getTitle(), 'Sender')
    self.assertEqual(document.getDestinationValue().getTitle(), 'Me')
    self.assertEqual(document.getContentInformation().get('Subject'),
                     'Test éncödèd email')
    self.assertEqual(document.getTitle(), 'Test éncödèd email')
    self.assertEqual(document.getTextContent(), 'cöntént\n')

Yusei Tahara's avatar
Yusei Tahara committed
571

572 573 574 575 576
## TODO:
##
##  def test_attachements(self):
##    event = self._ingestMail('with_attachements')
##
577

Yusei Tahara's avatar
Yusei Tahara committed
578 579 580
class TestCRMMailSend(ERP5TypeTestCase):
  """Test Mail Sending for CRM
  """
581 582
  def getTitle(self):
    return "CRM Mail Sending"
Yusei Tahara's avatar
Yusei Tahara committed
583 584

  def getBusinessTemplateList(self):
Yusei Tahara's avatar
Yusei Tahara committed
585 586
    # In this test, We will attach some document portal types in event.
    # So we add DMS and Web.
587 588 589 590 591 592 593
    return ('erp5_base',
            'erp5_ingestion',
            'erp5_ingestion_mysql_innodb_catalog',
            'erp5_crm',
            'erp5_web',
            'erp5_dms',
            )
Yusei Tahara's avatar
Yusei Tahara committed
594 595 596 597 598 599

  def afterSetUp(self):
    portal = self.portal

    # create customer organisation and person
    if 'customer' not in portal.organisation_module.objectIds():
600
      portal.organisation_module.newContent(
Yusei Tahara's avatar
Yusei Tahara committed
601 602 603
              id='customer',
              portal_type='Organisation',
              title='Customer')
604 605
    customer_organisation = portal.organisation_module.customer
    if 'recipient' not in portal.person_module.contentIds():
Yusei Tahara's avatar
Yusei Tahara committed
606
      portal.person_module.newContent(
607
              id='recipient',
608 609 610
              # The ',' below is to force quoting of the name in e-mail
              # addresses on Zope 2.12
              title='Recipient,',
Yusei Tahara's avatar
Yusei Tahara committed
611
              subordination_value=customer_organisation,
612 613 614
              default_email_text='recipient@example.com')
    if 'me' not in portal.person_module.contentIds():
      # also create the sender
Yusei Tahara's avatar
Yusei Tahara committed
615 616
      portal.person_module.newContent(
              id='me',
617 618 619
              # The ',' below is to force quoting of the name in e-mail
              # addresses on Zope 2.12
              title='Me,',
Yusei Tahara's avatar
Yusei Tahara committed
620 621 622 623 624 625 626 627
              default_email_text='me@erp5.org')

    # set preference
    default_pref = self.portal.portal_preferences.default_site_preference
    default_pref.setPreferredOoodocServerAddress(conversion_server_host[0])
    default_pref.setPreferredOoodocServerPortNumber(conversion_server_host[1])
    default_pref.setPreferredDocumentFileNameRegularExpression(FILE_NAME_REGULAR_EXPRESSION)
    default_pref.setPreferredDocumentReferenceRegularExpression(REFERENCE_REGULAR_EXPRESSION)
628 629
    if default_pref.getPreferenceState() == 'disabled':
      default_pref.enable()
Yusei Tahara's avatar
Yusei Tahara committed
630

631 632 633 634 635
    # 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'))

Yusei Tahara's avatar
Yusei Tahara committed
636
    # make sure customers are available to catalog
637
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
638 639 640
    self.tic()

  def beforeTearDown(self):
641
    transaction.abort()
Yusei Tahara's avatar
Yusei Tahara committed
642
    # clear modules if necessary
643 644
    for module in (self.portal.event_module,
                   self.portal.campaign_module,):
Yusei Tahara's avatar
Yusei Tahara committed
645
      module.manage_delObjects(list(module.objectIds()))
646
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
647 648
    self.tic()

649 650 651 652 653 654 655 656 657 658
  def test_MailFromMailMessageEvent(self):
    # passing start_action transition on event workflow will send an email to the
    # person as destination
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('A Mail')
    event.setTextContent('Mail Content')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
659
    transaction.commit()
660 661 662 663
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
664 665
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
666 667 668
    
    message = email.message_from_string(messageText)

669 670
    self.assertEquals('A Mail',
                      email.Header.decode_header(message['Subject'])[0][0])
671 672 673 674 675 676
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual('Mail Content', part.get_payload(decode=True))

677 678 679 680 681 682 683 684 685 686 687
    #
    # Test multiple recipients.
    #
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    # multiple recipients.
    event.setDestinationList(['person_module/recipient', 'person_module/me'])
    event.setTitle('A Mail')
    event.setTextContent('Mail Content')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
688
    transaction.commit()
689 690 691 692
    self.tic()
    last_message_1, last_message_2 = self.portal.MailHost._message_list[-2:]
    self.assertNotEquals((), last_message_1)
    self.assertNotEquals((), last_message_2)
693 694
    # check last message 1 and last message 2 (the order is random)
    # both should have 'From: Me'
695
    self.assertEquals(['"Me," <me@erp5.org>', '"Me," <me@erp5.org>'],
696 697
                      [x[0] for x in (last_message_1, last_message_2)])
    # one should have 'To: Me' and the other should have 'To: Recipient'
698
    self.assertEquals([['"Me," <me@erp5.org>'], ['"Recipient," <recipient@example.com>']],
699
                      sorted([x[1] for x in (last_message_1, last_message_2)]))
700

701 702 703 704 705 706 707 708 709 710 711
  def test_MailFromMailMessageEventNoSendMail(self):
    # passing start_action transition on event workflow will send an email to the
    # person as destination, unless you don't check "send_mail" box in the
    # workflow dialog
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('A Mail')
    event.setTextContent('Mail Content')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
712
    transaction.commit()
713 714 715 716 717 718 719 720
    self.tic()
    # no mail sent
    last_message = self.portal.MailHost._last_message

  def test_MailFromOtherEvents(self):
    # passing start_action transition on event workflow will not send an email
    # when the portal type is not Mail Message
    for ptype in [t for t in self.portal.getPortalEventTypeList()
721 722
        if t not in ('Mail Message', 'Document Ingestion Message',
          'Acknowledgement')]:
723 724 725 726 727 728 729
      event = self.portal.event_module.newContent(portal_type=ptype)
      event.setSource('person_module/me')
      event.setDestination('person_module/recipient')
      event.setTextContent('Hello !')
      self.portal.portal_workflow.doActionFor(event, 'start_action',
                                              send_mail=1)

730
      transaction.commit()
731 732 733 734
      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)

Rafael Monnerat's avatar
Rafael Monnerat committed
735 736 737
  def test_MailMarkPosted(self):
    # mark_started_action transition on event workflow will not send an email
    # even if the portal type is a Mail Message
738 739
    for ptype in [x for x in self.portal.getPortalEventTypeList() if x !=
        'Acknowledgement']:
Rafael Monnerat's avatar
Rafael Monnerat committed
740 741 742 743 744 745 746
      event = self.portal.event_module.newContent(portal_type=ptype)
      event.setSource('person_module/me')
      event.setDestination('person_module/recipient')
      event.setTextContent('Hello !')
      self.portal.portal_workflow.doActionFor(event, 'receive_action')
      self.portal.portal_workflow.doActionFor(event, 'mark_started_action')

747
      transaction.commit()
Rafael Monnerat's avatar
Rafael Monnerat committed
748 749 750 751 752
      self.tic()
      # this means no message have been set
      self.assertEquals((), self.portal.MailHost._last_message)


753
  def test_MailMessageHTML(self):
754 755
    # test sending a mail message edited as HTML (the default with FCKEditor),
    # then the mail should have HTML.
756 757 758 759 760 761 762
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTextFormat('text/html')
    event.setTextContent('Hello<br/>World')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
763
    transaction.commit()
764 765 766 767
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
768 769
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
770

771 772 773
    message = email.message_from_string(messageText)
    part = None
    for i in message.get_payload():
774
      if i.get_content_type()=='text/html':
775
        part = i
776 777
    self.assertNotEqual(part, None)
    self.assertEqual('<html><body>Hello<br/>World</body></html>', part.get_payload(decode=True))
778 779 780 781 782 783 784 785 786 787

  def test_MailMessageEncoding(self):
    # test sending a mail message with non ascii characters
    event = self.portal.event_module.newContent(portal_type='Mail Message')
    event.setSource('person_module/me')
    event.setDestination('person_module/recipient')
    event.setTitle('Héhé')
    event.setTextContent('Hàhà')
    self.portal.portal_workflow.doActionFor(event, 'start_action',
                                            send_mail=1)
788
    transaction.commit()
789 790 791 792
    self.tic()
    last_message = self.portal.MailHost._last_message
    self.assertNotEquals((), last_message)
    mfrom, mto, messageText = last_message
793 794
    self.assertEquals('"Me," <me@erp5.org>', mfrom)
    self.assertEquals(['"Recipient," <recipient@example.com>'], mto)
795 796 797
    
    message = email.message_from_string(messageText)

798 799
    self.assertEquals('Héhé',
                      email.Header.decode_header(message['Subject'])[0][0])
800 801 802 803 804 805
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual('Hàhà', part.get_payload(decode=True))

Yusei Tahara's avatar
Yusei Tahara committed
806
  def test_MailAttachmentPdf(self):
Yusei Tahara's avatar
Yusei Tahara committed
807 808 809
    """
    Make sure that pdf document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
810 811
    # Add a document which will be attached.

Yusei Tahara's avatar
Yusei Tahara committed
812 813 814 815 816
    def add_document(filename, id, container, portal_type):
      f = openTestFile(filename)
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document
Yusei Tahara's avatar
Yusei Tahara committed
817

Yusei Tahara's avatar
Yusei Tahara committed
818 819 820
    # pdf
    document_pdf = add_document('sample_attachment.pdf', '1',
                                self.portal.document_module, 'PDF')
Yusei Tahara's avatar
Yusei Tahara committed
821

822
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
838
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
839
               aggregate=document_pdf.getRelativeUrl(),
Yusei Tahara's avatar
Yusei Tahara committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # pdf
    self.assert_('sample_attachment.pdf' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.pdf':
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_pdf.getData()))
Yusei Tahara's avatar
Yusei Tahara committed
861 862

  def test_MailAttachmentText(self):
Yusei Tahara's avatar
Yusei Tahara committed
863 864 865
    """
    Make sure that text document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
866 867 868 869 870 871 872 873 874 875 876 877
    # Add a document which will be attached.

    def add_document(filename, id, container, portal_type):
      f = openTestFile(filename)
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # odt
    document_odt = add_document('sample_attachment.odt', '2',
                                self.portal.document_module, 'Text')
    
878
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
894
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
895 896 897 898 899 900 901 902 903 904 905 906 907 908
               aggregate=document_odt.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
Yusei Tahara's avatar
Yusei Tahara committed
909 910 911 912 913 914 915 916 917
    # odt
    self.assert_('sample_attachment.odt' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.odt':
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)

Yusei Tahara's avatar
Yusei Tahara committed
918
  def test_MailAttachmentFile(self):
Yusei Tahara's avatar
Yusei Tahara committed
919 920 921
    """
    Make sure that file document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
922 923 924 925 926 927 928 929 930 931 932 933
    # Add a document which will be attached.

    def add_document(filename, id, container, portal_type):
      f = openTestFile(filename)
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # zip
    document_zip = add_document('sample_attachment.zip', '3',
                                self.portal.document_module, 'File')

934
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
950
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
               aggregate=document_zip.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # zip
    self.assert_('sample_attachment.zip' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.zip':
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)

  def test_MailAttachmentImage(self):
Yusei Tahara's avatar
Yusei Tahara committed
975 976 977
    """
    Make sure that image document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
978 979 980 981 982 983 984 985 986 987 988 989
    # Add a document which will be attached.

    def add_document(filename, id, container, portal_type):
      f = openTestFile(filename)
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # gif
    document_gif = add_document('sample_attachment.gif', '4',
                                self.portal.image_module, 'Image')

990
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1006
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
               aggregate=document_gif.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # gif
    self.assert_('sample_attachment.gif' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.gif':
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_gif.getData()))

  def test_MailAttachmentWebPage(self):
Yusei Tahara's avatar
Yusei Tahara committed
1031 1032 1033
    """
    Make sure that webpage document is correctly attached in email
    """
Yusei Tahara's avatar
Yusei Tahara committed
1034 1035 1036 1037 1038 1039 1040
    # Add a document which will be attached.

    document_html = self.portal.web_page_module.newContent(id='5',
                                                           portal_type='Web Page')
    document_html.edit(text_content='<html><body>Hello world!</body></html>',
                       reference='sample_attachment.html')

1041
    transaction.commit()
Yusei Tahara's avatar
Yusei Tahara committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1057
               destination='person_module/recipient',
Yusei Tahara's avatar
Yusei Tahara committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
               aggregate=document_html.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # html
    self.assert_('sample_attachment.html' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.html':
        part = i
1079 1080 1081
    self.assertEqual(part.get_payload(decode=True),
                     str(document_html.getTextContent()))
    self.assertEqual(part.get_content_type(), 'text/html')
Yusei Tahara's avatar
Yusei Tahara committed
1082

Aurel's avatar
Aurel committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  def test_MailRespond(self):
    """
    Test we can answer an incoming event and quote it
    """
    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='incoming')
Yusei Tahara's avatar
Yusei Tahara committed
1096

Aurel's avatar
Aurel committed
1097 1098 1099
    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1100
               destination='person_module/recipient',
Aurel's avatar
Aurel committed
1101 1102 1103 1104 1105
               text_content='This is an advertisement mail.')
    first_event_id = event.getId()
    self.getWorkflowTool().doActionFor(event, 'respond_action', 
                                       respond_event_portal_type = "Mail Message",
                                       respond_event_title = "Answer",
1106
                                       respond_event_text_content="> This is an advertisement mail."
Aurel's avatar
Aurel committed
1107 1108 1109
                                       )

    self.assertEqual(event.getSimulationState(), "responded")
1110

Aurel's avatar
Aurel committed
1111 1112 1113 1114 1115 1116 1117
    # answer event must have been created
    self.assertEqual(len(self.portal.event_module), 2)
    for ev in self.portal.event_module.objectValues():
      if ev.getId() != first_event_id:
        answer_event = ev

    # check properties of answer event
1118
    self.assertEqual(answer_event.getSimulationState(), "started")
Aurel's avatar
Aurel committed
1119 1120
    self.assertEqual(answer_event.getCausality(), event.getRelativeUrl())
    self.assertEqual(answer_event.getDestination(), 'person_module/me')
1121
    self.assertEqual(answer_event.getSource(), 'person_module/recipient')
Aurel's avatar
Aurel committed
1122
    self.assertEqual(answer_event.getTextContent(), '> This is an advertisement mail.')
1123 1124
    self.assertEqual(answer_event.getFollowUpValue(), ticket)
    self.assert_(answer_event.getData() is not None)
Yusei Tahara's avatar
Yusei Tahara committed
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
  def test_MailAttachmentFileWithoutDMS(self):
    """
    Make sure that file document is correctly attached in email
    """
    # Add a document on a person which will be attached.

    def add_document(filename, id, container, portal_type):
      f = openTestFile(filename)
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # txt
    document_txt = add_document('sample_attachment.txt', '2',
                                self.portal.person_module['me'], 'File')

1142
    transaction.commit()
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1158
               destination='person_module/recipient',
1159 1160 1161 1162 1163 1164 1165 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
               aggregate=document_txt.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # txt
    self.assert_('sample_attachment.txt' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.txt':
        part = i
    self.assert_(len(part.get_payload(decode=True))>0)



  def test_MailAttachmentImageWithoutDMS(self):
    """
    Make sure that image document is correctly attached in email without dms
    """
    # Add a document on a person which will be attached.

    def add_document(filename, id, container, portal_type):
      f = openTestFile(filename)
      document = container.newContent(id=id, portal_type=portal_type)
      document.edit(file=f, reference=filename)
      return document

    # gif
    document_gif = add_document('sample_attachment.gif', '1',
                                self.portal.person_module['me'], 'Image')

1200
    transaction.commit()
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    self.tic()

    # Add a ticket
    ticket = self.portal.campaign_module.newContent(id='1',
                                                    portal_type='Campaign',
                                                    title='Advertisement')
    # Create a event
    ticket.Ticket_newEvent(portal_type='Mail Message',
                           title='Our new product',
                           description='Buy this now!',
                           direction='outgoing')

    # Set sender and attach a document to the event.
    event = self.portal.event_module.objectValues()[0]
    event.edit(source='person_module/me',
1216
               destination='person_module/recipient',
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
               aggregate=document_gif.getRelativeUrl(),
               text_content='This is an advertisement mail.')

    mail_text = event.send(download=True)

    # Check mail text.
    message = email.message_from_string(mail_text)
    part = None
    for i in message.get_payload():
      if i.get_content_type()=='text/plain':
        part = i
    self.assertEqual(part.get_payload(decode=True), event.getTextContent())

    # Check attachment
    # gif
    self.assert_('sample_attachment.gif' in 
                 [i.get_filename() for i in message.get_payload()])
    part = None
    for i in message.get_payload():
      if i.get_filename()=='sample_attachment.gif':
        part = i
    self.assertEqual(part.get_payload(decode=True), str(document_gif.getData()))

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  def test_cloneEvent(self):
    """
      All events uses after script and interaciton
      workflow add a test for clone
    """
    portal_type = "Mail Message"
    event = self.portal.event_module.newContent(portal_type=portal_type)
    event.setData("This is the context of the event...")
    self.stepTic()
    new_event = event.Base_createCloneDocument(batch_mode=1)
    self.failIf(new_event.hasFile())
    self.assertEquals(new_event.getData(), "")

1253

1254 1255
def test_suite():
  suite = unittest.TestSuite()
1256
  suite.addTest(unittest.makeSuite(TestCRM))
1257
  suite.addTest(unittest.makeSuite(TestCRMMailIngestion))
Yusei Tahara's avatar
Yusei Tahara committed
1258
  suite.addTest(unittest.makeSuite(TestCRMMailSend))
1259
  return suite