This file is indexed.

/usr/lib/python2.7/dist-packages/txdav/caldav/datastore/scheduling/imip/test/test_outbound.py is in calendarserver 5.2+dfsg-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
466
467
468
469
470
471
472
473
474
475
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
##
# Copyright (c) 2008-2014 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
from __future__ import print_function

from cStringIO import StringIO

from pycalendar.datetime import PyCalendarDateTime

from twisted.internet.defer import inlineCallbacks, succeed
from twisted.trial import unittest
from twisted.web.template import Element, renderer, flattenString

from twistedcaldav.config import config
from twistedcaldav.ical import Component

from txdav.caldav.datastore.scheduling.imip.outbound import IMIPInvitationWork
from txdav.caldav.datastore.scheduling.imip.outbound import MailSender
from txdav.caldav.datastore.scheduling.imip.outbound import StringFormatTemplateLoader
from txdav.common.datastore.test.util import buildStore

import email
from email.iterators import typed_subpart_iterator
import os


initialInviteText = u"""BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
UID:CFDD5E46-4F74-478A-9311-B3FF905449C3
DTSTART:20200325T154500Z
DTEND:20200325T164500Z
ATTENDEE;CN=Th\xe9 Attendee;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP=TRU
 E:mailto:attendee@example.com
ATTENDEE;CN=Th\xe9 Organizer;CUTYPE=INDIVIDUAL;EMAIL=organizer@example.com;P
 ARTSTAT=ACCEPTED:urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A
ATTENDEE;CN=An Attendee without CUTYPE;EMAIL=nocutype@example.com;PARTSTAT=A
 CCEPTED:urn:uuid:4DB528DC-3E60-44FA-9546-2A00FCDCFFAB
ATTENDEE;EMAIL=nocn@example.com;PARTSTAT=ACCEPTED:urn:uuid:A592CF8B-4FC8-4E4
 F-B543-B2F29A7EEB0B
ORGANIZER;CN=Th\xe9 Organizer;EMAIL=organizer@example.com:urn:uuid:C3B38B00-
 4166-11DD-B22C-A07C87E02F6A
SUMMARY:t\xe9sting outbound( )
DESCRIPTION:awesome description with "<" and "&"
END:VEVENT
END:VCALENDAR
"""

inviteTextNoTimezone = u"""BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
UID:CFDD5E46-4F74-478A-9311-B3FF905449C3
DTSTART;TZID=America/New_York:20200325T154500
DTEND;TZID=America/New_York:20200325T164500Z
ATTENDEE;CN=Th\xe9 Attendee;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP=TRU
 E:mailto:attendee@example.com
ATTENDEE;CN=Th\xe9 Organizer;CUTYPE=INDIVIDUAL;EMAIL=organizer@example.com;P
 ARTSTAT=ACCEPTED:urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A
ATTENDEE;CN=An Attendee without CUTYPE;EMAIL=nocutype@example.com;PARTSTAT=A
 CCEPTED:urn:uuid:4DB528DC-3E60-44FA-9546-2A00FCDCFFAB
ATTENDEE;EMAIL=nocn@example.com;PARTSTAT=ACCEPTED:urn:uuid:A592CF8B-4FC8-4E4
 F-B543-B2F29A7EEB0B
ORGANIZER;CN=Th\xe9 Organizer;EMAIL=organizer@example.com:urn:uuid:C3B38B00-
 4166-11DD-B22C-A07C87E02F6A
SUMMARY:t\xe9sting outbound( )
DESCRIPTION:awesome description with "<" and "&"
END:VEVENT
END:VCALENDAR
"""

inviteTextWithTimezone = u"""BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
BEGIN:VTIMEZONE
TZID:America/New_York
X-LIC-LOCATION:America/New_York
BEGIN:STANDARD
DTSTART:18831118T120358
RDATE:18831118T120358
TZNAME:EST
TZOFFSETFROM:-045602
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19180331T020000
RRULE:FREQ=YEARLY;UNTIL=19190330T070000Z;BYDAY=-1SU;BYMONTH=3
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19181027T020000
RRULE:FREQ=YEARLY;UNTIL=19191026T060000Z;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:STANDARD
DTSTART:19200101T000000
RDATE:19200101T000000
RDATE:19420101T000000
RDATE:19460101T000000
RDATE:19670101T000000
TZNAME:EST
TZOFFSETFROM:-0500
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19200328T020000
RDATE:19200328T020000
RDATE:19740106T020000
RDATE:19750223T020000
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19201031T020000
RDATE:19201031T020000
RDATE:19450930T020000
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19210424T020000
RRULE:FREQ=YEARLY;UNTIL=19410427T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19210925T020000
RRULE:FREQ=YEARLY;UNTIL=19410928T060000Z;BYDAY=-1SU;BYMONTH=9
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19420209T020000
RDATE:19420209T020000
TZNAME:EWT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:19450814T190000
RDATE:19450814T190000
TZNAME:EPT
TZOFFSETFROM:-0400
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:19460428T020000
RRULE:FREQ=YEARLY;UNTIL=19660424T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19460929T020000
RRULE:FREQ=YEARLY;UNTIL=19540926T060000Z;BYDAY=-1SU;BYMONTH=9
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:STANDARD
DTSTART:19551030T020000
RRULE:FREQ=YEARLY;UNTIL=19661030T060000Z;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19670430T020000
RRULE:FREQ=YEARLY;UNTIL=19730429T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19671029T020000
RRULE:FREQ=YEARLY;UNTIL=20061029T060000Z;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19760425T020000
RRULE:FREQ=YEARLY;UNTIL=19860427T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:19870405T020000
RRULE:FREQ=YEARLY;UNTIL=20060402T070000Z;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:20070311T020000
RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20071104T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:CFDD5E46-4F74-478A-9311-B3FF905449C3
DTSTART;TZID=America/New_York:20200325T154500
DTEND;TZID=America/New_York:20200325T164500Z
ATTENDEE;CN=Th\xe9 Attendee;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP=TRU
 E:mailto:attendee@example.com
ATTENDEE;CN=Th\xe9 Organizer;CUTYPE=INDIVIDUAL;EMAIL=organizer@example.com;P
 ARTSTAT=ACCEPTED:urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A
ATTENDEE;CN=An Attendee without CUTYPE;EMAIL=nocutype@example.com;PARTSTAT=A
 CCEPTED:urn:uuid:4DB528DC-3E60-44FA-9546-2A00FCDCFFAB
ATTENDEE;EMAIL=nocn@example.com;PARTSTAT=ACCEPTED:urn:uuid:A592CF8B-4FC8-4E4
 F-B543-B2F29A7EEB0B
ORGANIZER;CN=Th\xe9 Organizer;EMAIL=organizer@example.com:urn:uuid:C3B38B00-
 4166-11DD-B22C-A07C87E02F6A
SUMMARY:t\xe9sting outbound( )
DESCRIPTION:awesome description with "<" and "&"
END:VEVENT
END:VCALENDAR
"""

ORGANIZER = "urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A"
ATTENDEE = "mailto:attendee@example.com"
ICALUID = "CFDD5E46-4F74-478A-9311-B3FF905449C3"

class DummySMTPSender(object):

    def __init__(self):
        self.reset()
        self.shouldSucceed = True


    def reset(self):
        self.sendMessageCalled = False
        self.fromAddr = None
        self.toAddr = None
        self.msgId = None
        self.message = None


    def sendMessage(self, fromAddr, toAddr, msgId, message):
        self.sendMessageCalled = True
        self.fromAddr = fromAddr
        self.toAddr = toAddr
        self.msgId = msgId
        self.message = message
        return succeed(self.shouldSucceed)



class OutboundTests(unittest.TestCase):

    @inlineCallbacks
    def setUp(self):
        self.store = yield buildStore(self, None)
        self.directory = self.store.directoryService()
        self.sender = MailSender("server@example.com", 7, DummySMTPSender(),
            language="en")

        def _getSender(ignored):
            return self.sender
        self.patch(IMIPInvitationWork, "getMailSender", _getSender)

        self.wp = None
        self.store.queuer.callWithNewProposals(self._proposalCallback)


    def _proposalCallback(self, wp):
        self.wp = wp


    @inlineCallbacks
    def test_work(self):
        txn = self.store.newTransaction()
        wp = (yield txn.enqueue(IMIPInvitationWork,
            fromAddr=ORGANIZER,
            toAddr=ATTENDEE,
            icalendarText=initialInviteText.replace("\n", "\r\n"),
        ))
        self.assertEquals(wp, self.wp)
        yield txn.commit()
        yield wp.whenExecuted()

        txn = self.store.newTransaction()
        token = (yield txn.imipGetToken(
            ORGANIZER,
            ATTENDEE,
            ICALUID
        ))
        self.assertTrue(token)
        organizer, attendee, icaluid = (yield txn.imipLookupByToken(token))[0]
        yield txn.commit()
        self.assertEquals(organizer, ORGANIZER)
        self.assertEquals(attendee, ATTENDEE)
        self.assertEquals(icaluid, ICALUID)


    @inlineCallbacks
    def test_workFailure(self):
        self.sender.smtpSender.shouldSucceed = False

        txn = self.store.newTransaction()
        wp = (yield txn.enqueue(IMIPInvitationWork,
            fromAddr=ORGANIZER,
            toAddr=ATTENDEE,
            icalendarText=initialInviteText.replace("\n", "\r\n"),
        ))
        yield txn.commit()
        yield wp.whenExecuted()
        # Verify a new work proposal was not created
        self.assertEquals(wp, self.wp)


    def _interceptEmail(self, inviteState, calendar, orgEmail, orgCn,
        attendees, fromAddress, replyToAddress, toAddress, language="en"):
        self.inviteState = inviteState
        self.calendar = calendar
        self.orgEmail = orgEmail
        self.orgCn = orgCn
        self.attendees = attendees
        self.fromAddress = fromAddress
        self.replyToAddress = replyToAddress
        self.toAddress = toAddress
        self.language = language
        self.results = self._actualGenerateEmail(inviteState, calendar,
            orgEmail, orgCn, attendees, fromAddress, replyToAddress, toAddress,
            language=language)
        return self.results


    @inlineCallbacks
    def test_outbound(self):
        """
        Make sure outbound( ) stores tokens properly so they can be looked up
        """

        config.Scheduling.iMIP.Sending.Address = "server@example.com"
        self.patch(config.Localization, "LocalesDirectory", os.path.join(os.path.dirname(__file__), "locales"))
        self._actualGenerateEmail = self.sender.generateEmail
        self.patch(self.sender, "generateEmail", self._interceptEmail)

        data = (
            # Initial invite
            (
                initialInviteText,
                "CFDD5E46-4F74-478A-9311-B3FF905449C3",
                "urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A",
                "mailto:attendee@example.com",
                "new",
                "organizer@example.com",
                u"Th\xe9 Organizer",
                [
                    (u'Th\xe9 Attendee', u'attendee@example.com'),
                    (u'Th\xe9 Organizer', u'organizer@example.com'),
                    (u'An Attendee without CUTYPE', u'nocutype@example.com'),
                    (None, u'nocn@example.com'),
                ],
                u"Th\xe9 Organizer <organizer@example.com>",
                "=?utf-8?q?Th=C3=A9_Organizer_=3Corganizer=40example=2Ecom=3E?=",
                "attendee@example.com",
            ),

            # Update
            (
                """BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
UID:CFDD5E46-4F74-478A-9311-B3FF905449C3
DTSTART:20100325T154500Z
DTEND:20100325T164500Z
ATTENDEE;CN=The Attendee;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:
 mailto:attendee@example.com
ATTENDEE;CN=The Organizer;CUTYPE=INDIVIDUAL;EMAIL=organizer@example.com;PAR
 TSTAT=ACCEPTED:urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A
ORGANIZER;CN=The Organizer;EMAIL=organizer@example.com:urn:uuid:C3B38B00-41
 66-11DD-B22C-A07C87E02F6A
SUMMARY:testing outbound( ) *update*
END:VEVENT
END:VCALENDAR
""",
                "CFDD5E46-4F74-478A-9311-B3FF905449C3",
                "urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A",
                "mailto:attendee@example.com",
                "update",
                "organizer@example.com",
                "The Organizer",
                [
                    (u'The Attendee', u'attendee@example.com'),
                    (u'The Organizer', u'organizer@example.com')
                ],
                "The Organizer <organizer@example.com>",
                "The Organizer <organizer@example.com>",
                "attendee@example.com",
            ),

            # Reply
            (
                """BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
UID:DFDD5E46-4F74-478A-9311-B3FF905449C4
DTSTART:20100325T154500Z
DTEND:20100325T164500Z
ATTENDEE;CN=The Attendee;CUTYPE=INDIVIDUAL;EMAIL=attendee@example.com;PARTST
 AT=ACCEPTED:urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A
ORGANIZER;CN=The Organizer;EMAIL=organizer@example.com:mailto:organizer@exam
 ple.com
SUMMARY:testing outbound( ) *reply*
END:VEVENT
END:VCALENDAR
""",
                None,
                "urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A",
                "mailto:organizer@example.com",
                "reply",
                "organizer@example.com",
                "The Organizer",
                [
                    (u'The Attendee', u'attendee@example.com'),
                ],
                "attendee@example.com",
                "attendee@example.com",
                "organizer@example.com",
            ),

        )
        for (inputCalendar, UID, inputOriginator, inputRecipient, inviteState,
            outputOrganizerEmail, outputOrganizerName, outputAttendeeList,
            outputFrom, encodedFrom, outputRecipient) in data:

            txn = self.store.newTransaction()
            yield self.sender.outbound(
                txn,
                inputOriginator,
                inputRecipient,
                Component.fromString(inputCalendar.replace("\n", "\r\n")),
                onlyAfter=PyCalendarDateTime(2010, 1, 1, 0, 0, 0)
            )
            yield txn.commit()

            msg = email.message_from_string(self.sender.smtpSender.message)
            self.assertEquals(msg["From"], encodedFrom)
            self.assertEquals(self.inviteState, inviteState)
            self.assertEquals(self.orgEmail, outputOrganizerEmail)
            self.assertEquals(self.orgCn, outputOrganizerName)
            self.assertEquals(self.attendees, outputAttendeeList)
            self.assertEquals(self.fromAddress, outputFrom)
            self.assertEquals(self.toAddress, outputRecipient)

            if UID: # The organizer is local, and server is sending to remote
                    # attendee
                txn = self.store.newTransaction()
                token = (yield txn.imipGetToken(inputOriginator, inputRecipient,
                    UID))
                yield txn.commit()
                self.assertNotEquals(token, None)
                self.assertEquals(msg["Reply-To"],
                    "server+%s@example.com" % (token,))

                # Make sure attendee property for organizer exists and matches
                # the CUA of the organizer property
                orgValue = self.calendar.getOrganizerProperty().value()
                self.assertEquals(
                    orgValue,
                    self.calendar.getAttendeeProperty([orgValue]).value()
                )

            else: # Reply only -- the attendee is local, and server is sending reply to remote organizer

                self.assertEquals(msg["Reply-To"], self.fromAddress)

            # Check that we don't send any messages for events completely in
            # the past.
            self.sender.smtpSender.reset()
            txn = self.store.newTransaction()
            yield self.sender.outbound(
                txn,
                inputOriginator,
                inputRecipient,
                Component.fromString(inputCalendar.replace("\n", "\r\n")),
                onlyAfter=PyCalendarDateTime(2021, 1, 1, 0, 0, 0)
            )
            yield txn.commit()
            self.assertFalse(self.sender.smtpSender.sendMessageCalled)


    @inlineCallbacks
    def test_tokens(self):
        txn = self.store.newTransaction()
        token = (yield txn.imipLookupByToken("xyzzy"))
        yield txn.commit()
        self.assertEquals(token, [])

        txn = self.store.newTransaction()
        token1 = (yield txn.imipCreateToken("organizer", "attendee", "icaluid"))
        yield txn.commit()

        txn = self.store.newTransaction()
        token2 = (yield txn.imipGetToken("organizer", "attendee", "icaluid"))
        yield txn.commit()
        self.assertEquals(token1, token2)

        txn = self.store.newTransaction()
        self.assertEquals((yield txn.imipLookupByToken(token1)),
            [["organizer", "attendee", "icaluid"]])
        yield txn.commit()

        txn = self.store.newTransaction()
        yield txn.imipRemoveToken(token1)
        yield txn.commit()

        txn = self.store.newTransaction()
        self.assertEquals((yield txn.imipLookupByToken(token1)), [])
        yield txn.commit()


    @inlineCallbacks
    def test_mailtoTokens(self):
        """
        Make sure old mailto tokens are still honored
        """

        organizerEmail = "mailto:organizer@example.com"

        # Explictly store a token with mailto: CUA for organizer
        # (something that doesn't happen any more, but did in the past)
        txn = self.store.newTransaction()
        origToken = (yield txn.imipCreateToken(organizerEmail,
            "mailto:attendee@example.com",
            "CFDD5E46-4F74-478A-9311-B3FF905449C3"
            )
        )
        yield txn.commit()

        inputCalendar = initialInviteText
        UID = "CFDD5E46-4F74-478A-9311-B3FF905449C3"
        inputOriginator = "urn:uuid:C3B38B00-4166-11DD-B22C-A07C87E02F6A"
        inputRecipient = "mailto:attendee@example.com"

        txn = self.store.newTransaction()
        yield self.sender.outbound(txn, inputOriginator, inputRecipient,
            Component.fromString(inputCalendar.replace("\n", "\r\n")),
            onlyAfter=PyCalendarDateTime(2010, 1, 1, 0, 0, 0))

        # Verify we didn't create a new token...
        txn = self.store.newTransaction()
        token = (yield txn.imipGetToken(inputOriginator, inputRecipient, UID))
        yield txn.commit()
        self.assertEquals(token, None)

        # But instead kept the old one...
        txn = self.store.newTransaction()
        token = (yield txn.imipGetToken(organizerEmail, inputRecipient, UID))
        yield txn.commit()
        self.assertEquals(token, origToken)


    def generateSampleEmail(self, caltext=initialInviteText):
        """
        Invoke L{MailHandler.generateEmail} and parse the result.
        """
        calendar = Component.fromString(caltext)
        msgID, msgTxt = self.sender.generateEmail(
            inviteState='new',
            calendar=calendar,
            orgEmail=u"user01@localhost",
            orgCN=u"User Z\xe9ro One",
            attendees=[(u"Us\xe9r One", "user01@localhost"),
                       (u"User 2", "user02@localhost")],
            fromAddress="user01@localhost",
            replyToAddress="imip-system@localhost",
            toAddress="user03@localhost",
        )
        message = email.message_from_string(msgTxt)
        return msgID, message


    def test_generateEmail(self):
        """
        L{MailHandler.generateEmail} generates a MIME-formatted email with a
        text/plain part, a text/html part, and a text/calendar part.
        """
        msgID, message = self.generateSampleEmail()
        self.assertEquals(message['Message-ID'], msgID)
        expectedTypes = set(["text/plain", "text/html", "text/calendar"])
        actualTypes = set([
            part.get_content_type() for part in message.walk()
            if part.get_content_type().startswith("text/")
        ])
        self.assertEquals(actualTypes, expectedTypes)


    def test_alwaysIncludeTimezones(self):
        """
        L{MailHandler.generateEmail} generates a MIME-formatted email with a
        text/plain part, a text/html part, and a text/calendar part.
        """
        _ignore, message = self.generateSampleEmail(inviteTextWithTimezone)
        calparts = tuple(typed_subpart_iterator(message, "text", "calendar"))
        self.assertEqual(len(calparts), 1)
        caldata = calparts[0].get_payload(decode=True)
        self.assertTrue("BEGIN:VTIMEZONE" in caldata)
        self.assertTrue("TZID:America/New_York" in caldata)

        _ignore, message = self.generateSampleEmail(inviteTextNoTimezone)
        calparts = tuple(typed_subpart_iterator(message, "text", "calendar"))
        self.assertEqual(len(calparts), 1)
        caldata = calparts[0].get_payload(decode=True)
        self.assertTrue("BEGIN:VTIMEZONE" in caldata)
        self.assertTrue("TZID:America/New_York" in caldata)


    def test_emailEncoding(self):
        """
        L{MailHandler.generateEmail} will preserve any non-ASCII characters
        present in the fields that it formats in the message body.
        """
        _ignore_msgID, message = self.generateSampleEmail()
        textPart = partByType(message, "text/plain")
        htmlPart = partByType(message, "text/html")

        plainText = textPart.get_payload(decode=True).decode(
            textPart.get_content_charset()
        )
        htmlText = htmlPart.get_payload(decode=True).decode(
            htmlPart.get_content_charset()
        )

        self.assertIn(u"Us\u00e9r One", plainText)
        self.assertIn(u'<a href="mailto:user01@localhost">Us\u00e9r One</a>',
                      htmlText)

        # The same assertion, but with the organizer's form.
        self.assertIn(
            u'<a href="mailto:user01@localhost">User Z\u00e9ro One</a>',
            htmlText)


    def test_emailQuoting(self):
        """
        L{MailHandler.generateEmail} will HTML-quote all relevant fields in the
        HTML part, but not the text/plain part.
        """
        _ignore_msgID, message = self.generateSampleEmail()
        htmlPart = partByType(message, "text/html").get_payload(decode=True)
        plainPart = partByType(message, "text/plain").get_payload(decode=True)
        expectedPlain = 'awesome description with "<" and "&"'
        expectedHTML = expectedPlain.replace("&", "&amp;").replace("<", "&lt;")

        self.assertIn(expectedPlain, plainPart)
        self.assertIn(expectedHTML, htmlPart)


    def test_stringFormatTemplateLoader(self):
        """
        L{StringFormatTemplateLoader.load} will convert a template with
        C{%(x)s}-format slots by converting it to a template with C{<t:slot
        name="x" />} slots, and a renderer on the document element named
        according to the constructor argument.
        """
        class StubElement(Element):
            loader = StringFormatTemplateLoader(
                lambda : StringIO(
                    "<test><alpha>%(slot1)s</alpha>%(other)s</test>"
                ),
                "testRenderHere"
            )

            @renderer
            def testRenderHere(self, request, tag):
                return tag.fillSlots(slot1="hello",
                                     other="world")
        result = []
        flattenString(None, StubElement()).addCallback(result.append)
        self.assertEquals(result,
                          ["<test><alpha>hello</alpha>world</test>"])


    def test_templateLoaderWithAttributes(self):
        """
        L{StringFormatTemplateLoader.load} will convert a template with
        C{%(x)s}-format slots inside attributes into t:attr elements containing
        t:slot slots.
        """
        class StubElement(Element):
            loader = StringFormatTemplateLoader(
                lambda : StringIO(
                    '<test><alpha beta="before %(slot1)s after">inner</alpha>'
                    '%(other)s</test>'
                ),
                "testRenderHere"
            )

            @renderer
            def testRenderHere(self, request, tag):
                return tag.fillSlots(slot1="hello",
                                     other="world")
        result = []
        flattenString(None, StubElement()).addCallback(result.append)
        self.assertEquals(result,
                          ['<test><alpha beta="before hello after">'
                           'inner</alpha>world</test>'])


    def test_templateLoaderTagSoup(self):
        """
        L{StringFormatTemplateLoader.load} will convert a template with
        C{%(x)s}-format slots into t:slot slots, and render a well-formed output
        document, even if the input is malformed (i.e. missing necessary closing
        tags).
        """
        class StubElement(Element):
            loader = StringFormatTemplateLoader(
                lambda : StringIO(
                    '<test><alpha beta="before %(slot1)s after">inner</alpha>'
                    '%(other)s'
                ),
                "testRenderHere"
            )

            @renderer
            def testRenderHere(self, request, tag):
                return tag.fillSlots(slot1="hello",
                                     other="world")
        result = []
        flattenString(None, StubElement()).addCallback(result.append)
        self.assertEquals(result,
                          ['<test><alpha beta="before hello after">'
                           'inner</alpha>world</test>'])



def partByType(message, contentType):
    """
    Retrieve a MIME part from an L{email.message.Message} based on a content
    type.
    """
    for part in message.walk():
        if part.get_content_type() == contentType:
            return part
    raise KeyError(contentType)