This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
test_sql.py
10045 lines (8913 loc) · 336 KB
/
test_sql.py
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##
# Copyright (c) 2010-2015 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.
##
"""
Tests for txdav.caldav.datastore.postgres, mostly based on
L{txdav.caldav.datastore.test.common}.
"""
from pycalendar.datetime import DateTime
from pycalendar.timezone import Timezone
from pycalendar.value import Value
from txweb2 import responsecode
from txweb2.http_headers import MimeType
from txweb2.stream import MemoryStream
from twisted.python.filepath import FilePath
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue, DeferredList, \
succeed, maybeDeferred
from twisted.internet.task import deferLater, Clock
from twisted.trial import unittest
from twistedcaldav import caldavxml, ical
from twistedcaldav.caldavxml import CalendarDescription
from twistedcaldav.stdconfig import config
from twistedcaldav.dateops import datetimeMktime
from twistedcaldav.ical import Component, normalize_iCalStr, diff_iCalStrs, Property
from twistedcaldav.instance import InvalidOverriddenInstanceError
from twistedcaldav.timezones import TimezoneCache, readVTZ, TimezoneException
from txdav.base.propertystore.base import PropertyName
from txdav.caldav.datastore.query.filter import Filter
from txdav.caldav.datastore.scheduling.caldav.scheduler import CalDAVScheduler
from txdav.caldav.datastore.scheduling.cuaddress import RemoteCalendarUser, \
LocalCalendarUser
from txdav.caldav.datastore.scheduling.implicit import ImplicitScheduler
from txdav.caldav.datastore.scheduling.itip import iTIPRequestStatus
from txdav.caldav.datastore.scheduling.processing import ImplicitProcessor
from txdav.caldav.datastore.scheduling.scheduler import ScheduleResponseQueue
from txdav.caldav.datastore.sql import CalendarStoreFeatures, CalendarObject
from txdav.common.datastore.sql import ECALENDARTYPE, CommonObjectResource, \
CommonStoreTransactionMonitor
from txdav.common.datastore.sql_tables import schema, _BIND_MODE_DIRECT, \
_BIND_STATUS_ACCEPTED, _TRANSP_OPAQUE, _BIND_MODE_WRITE
from txdav.caldav.datastore.test.common import CommonTests as CalendarCommonTests, \
test_event_text, cal1Root
from txdav.caldav.datastore.test.test_file import setUpCalendarStore
from txdav.caldav.datastore.test.util import DateTimeSubstitutionsMixin
from txdav.common.datastore.test.util import populateCalendarsFrom, \
CommonCommonTests, updateToCurrentYear
from txdav.caldav.datastore.util import _migrateCalendar, migrateHome
from txdav.caldav.icalendarstore import ComponentUpdateState, InvalidDefaultCalendar, \
InvalidSplit, UnknownTimezone
from txdav.common.icommondatastore import NoSuchObjectResourceError, \
InvalidComponentForStoreError
from txdav.idav import ChangeCategory
from txdav.xml.rfc2518 import GETContentLanguage, ResourceType
from twext.enterprise.dal.syntax import Select, Parameter, Insert, Delete, \
Update
from twext.enterprise.ienterprise import AlreadyFinishedError
from twext.enterprise.jobqueue import JobItem
from twext.enterprise.util import parseSQLTimestamp
import datetime
import os
class CalendarSQLStorageTests(CalendarCommonTests, unittest.TestCase):
"""
Calendar SQL storage tests.
"""
@inlineCallbacks
def setUp(self):
yield super(CalendarSQLStorageTests, self).setUp()
yield self.buildStoreAndDirectory()
yield self.populate()
self.nowYear = {"now": DateTime.getToday().getYear()}
@inlineCallbacks
def populate(self):
yield populateCalendarsFrom(self.requirements, self.storeUnderTest())
self.notifierFactory.reset()
@inlineCallbacks
def assertCalendarsSimilar(self, a, b, bCalendarFilter=None):
"""
Assert that two calendars have a similar structure (contain the same
events).
"""
@inlineCallbacks
def namesAndComponents(x, filter=lambda x: x.component()):
result = {}
for fromObj in (yield x.calendarObjects()):
result[fromObj.name()] = yield filter(fromObj)
returnValue(result)
if bCalendarFilter is not None:
extra = [bCalendarFilter]
else:
extra = []
self.assertEquals((yield namesAndComponents(a)),
(yield namesAndComponents(b, *extra)))
def assertPropertiesSimilar(self, a, b, disregard=[]):
"""
Assert that two objects with C{properties} methods have similar
properties.
@param disregard: a list of L{PropertyName} keys to discard from both
input and output.
"""
def sanitize(x):
result = dict(x.properties().items())
for key in disregard:
result.pop(key, None)
return result
self.assertEquals(sanitize(a), sanitize(b))
def fileTransaction(self):
"""
Create a file-backed calendar transaction, for migration testing.
"""
setUpCalendarStore(self)
fileStore = self.calendarStore
txn = fileStore.newTransaction()
self.addCleanup(txn.commit)
return txn
@inlineCallbacks
def test_purgingHome(self):
"""
Purging a calendar homes changes its status.
"""
home = yield self.homeUnderTest(name="home1")
self.assertFalse(home.purging())
self.assertFalse(home.external())
yield home.purge()
self.assertTrue(home.purging())
self.assertFalse(home.external())
yield self.commit()
home = yield self.homeUnderTest(name="home1")
self.assertTrue(home is not None)
yield self.commit()
@inlineCallbacks
def test_migrateCalendarFromFile(self):
"""
C{_migrateCalendar()} can migrate a file-backed calendar to a database-
backed calendar.
"""
fromCalendar = yield (yield self.fileTransaction().calendarHomeWithUID(
"home1")).calendarWithName("calendar_1")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True)
toCalendar = yield toHome.calendarWithName("calendar")
yield _migrateCalendar(fromCalendar, toCalendar,
lambda x: x.component())
yield self.assertCalendarsSimilar(fromCalendar, toCalendar)
@inlineCallbacks
def test_migrateBadCalendarFromFile(self):
"""
C{_migrateCalendar()} can migrate a file-backed calendar to a database-
backed calendar. We need to test what happens when there is "bad" calendar data
present in the file-backed calendar.
"""
fromCalendar = yield (yield self.fileTransaction().calendarHomeWithUID(
"home_bad")).calendarWithName("calendar_bad")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True)
toCalendar = yield toHome.calendarWithName("calendar")
ok, bad = (yield _migrateCalendar(fromCalendar, toCalendar, lambda x: x.component()))
self.assertEqual(ok, 1)
self.assertEqual(bad, 2)
@inlineCallbacks
def test_migrateRecurrenceFixCalendarFromFile(self):
"""
C{_migrateCalendar()} can migrate a file-backed calendar to a database-
backed calendar. We need to test what happens when there is "bad" calendar data
present in the file-backed calendar with a broken recurrence-id that we can fix.
"""
self.storeUnderTest().setMigrating(True)
fromCalendar = yield (yield self.fileTransaction().calendarHomeWithUID(
"home_bad")).calendarWithName("calendar_fix_recurrence")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True)
toCalendar = yield toHome.calendarWithName("calendar")
ok, bad = (yield _migrateCalendar(fromCalendar, toCalendar, lambda x: x.component()))
self.assertEqual(ok, 3)
self.assertEqual(bad, 0)
self.transactionUnderTest().commit()
self.storeUnderTest().setMigrating(False)
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True)
toCalendar = yield toHome.calendarWithName("calendar")
toResource = yield toCalendar.calendarObjectWithName("1.ics")
caldata = yield toResource.componentForUser()
self.assertEqual(str(caldata), """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
BEGIN:VTIMEZONE
TZID:US/Eastern
LAST-MODIFIED:20040110T032845Z
BEGIN:DAYLIGHT
DTSTART:20000404T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20001026T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:uid2
DTSTART;TZID=US/Eastern:%(now)s0102T140000
DURATION:PT1H
CREATED:20060102T190000Z
DTSTAMP:20051222T210507Z
RDATE;TZID=US/Eastern:%(now)s0104T160000
RRULE:FREQ=DAILY;COUNT=5
SUMMARY:event 6-ctr
END:VEVENT
BEGIN:VEVENT
UID:uid2
RECURRENCE-ID;TZID=US/Eastern:%(now)s0104T160000
DTSTART;TZID=US/Eastern:%(now)s0104T160000
DURATION:PT1H
CREATED:20060102T190000Z
DESCRIPTION:Some notes
DTSTAMP:20051222T210507Z
SUMMARY:event 6-ctr changed again
BEGIN:VALARM
ACTION:AUDIO
TRIGGER;RELATED=START:-PT10M
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n") % self.nowYear)
toResource = yield toCalendar.calendarObjectWithName("2.ics")
caldata = yield toResource.componentForUser()
self.assertEqual(str(caldata), """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
BEGIN:VTIMEZONE
TZID:US/Eastern
LAST-MODIFIED:20040110T032845Z
BEGIN:DAYLIGHT
DTSTART:20000404T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20001026T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:uid3
DTSTART;TZID=US/Eastern:%(now)s0102T140000
DURATION:PT1H
ATTENDEE:urn:uuid:home_bad
CREATED:20060102T190000Z
DTSTAMP:20051222T210507Z
ORGANIZER:urn:uuid:home_bad
RRULE:FREQ=DAILY;COUNT=5
SUMMARY:event 6-ctr
END:VEVENT
BEGIN:VEVENT
UID:uid3
RECURRENCE-ID;TZID=US/Eastern:%(now)s0104T140000
DTSTART;TZID=US/Eastern:%(now)s0104T160000
DURATION:PT1H
CREATED:20060102T190000Z
DESCRIPTION:Some notes
DTSTAMP:20051222T210507Z
ORGANIZER:urn:uuid:home_bad
SUMMARY:event 6-ctr changed again
BEGIN:VALARM
ACTION:AUDIO
TRIGGER;RELATED=START:-PT10M
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n") % self.nowYear)
toResource = yield toCalendar.calendarObjectWithName("3.ics")
caldata = yield toResource.componentForUser()
self.assertEqual(str(caldata), """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
BEGIN:VTIMEZONE
TZID:US/Eastern
LAST-MODIFIED:20040110T032845Z
BEGIN:DAYLIGHT
DTSTART:20000404T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20001026T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:uid4
DTSTART;TZID=US/Eastern:%(now)s0104T160000
DURATION:PT1H
CREATED:20060102T190000Z
DESCRIPTION:Some notes
DTSTAMP:20051222T210507Z
RDATE;TZID=US/Eastern:%(now)s0104T160000
SUMMARY:event 6-ctr changed again
END:VEVENT
BEGIN:VEVENT
UID:uid4
RECURRENCE-ID;TZID=US/Eastern:%(now)s0104T160000
DTSTART;TZID=US/Eastern:%(now)s0104T160000
DURATION:PT1H
CREATED:20060102T190000Z
DESCRIPTION:Some notes
DTSTAMP:20051222T210507Z
SUMMARY:event 6-ctr changed again
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n") % self.nowYear)
@inlineCallbacks
def test_migrateDuplicateAttachmentsCalendarFromFile(self):
"""
C{_migrateCalendar()} can migrate a file-backed calendar to a database-
backed calendar. Test that migrating a calendar containing duplicate attachments
will de-duplicate those attachments and proceed without error.
"""
# Need to tweak config and settings to setup dropbox to work
self.patch(config, "EnableDropBox", True)
self.patch(config, "EnableManagedAttachments", False)
self._sqlCalendarStore.enableManagedAttachments = False
txn = self._sqlCalendarStore.newTransaction()
cs = schema.CALENDARSERVER
yield Delete(
From=cs,
Where=cs.NAME == "MANAGED-ATTACHMENTS"
).on(txn)
yield txn.commit()
fromCalendar = yield (yield self.fileTransaction().calendarHomeWithUID(
"home_attachments")).calendarWithName("calendar_1")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"home_attachments", create=True)
toCalendar = yield toHome.calendarWithName("calendar")
ok, bad = (yield _migrateCalendar(fromCalendar, toCalendar, lambda x: x.component()))
self.assertEqual(ok, 3)
self.assertEqual(bad, 0)
@inlineCallbacks
def test_migrateCalendarFromFile_Transparency(self):
"""
C{_migrateCalendar()} can migrate a file-backed calendar to a database-
backed calendar.
"""
fromCalendar = yield (yield self.fileTransaction().calendarHomeWithUID(
"home1")).calendarWithName("calendar_1")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True)
toCalendar = yield toHome.calendarWithName("calendar")
yield _migrateCalendar(fromCalendar, toCalendar,
lambda x: x.component())
filter = caldavxml.Filter(
caldavxml.ComponentFilter(
caldavxml.ComponentFilter(
caldavxml.TimeRange(start="%(now)s0201T000000Z" % self.nowYear, end="%(now)s0202T000000Z" % self.nowYear),
name=("VEVENT", "VFREEBUSY", "VAVAILABILITY"),
),
name="VCALENDAR",
)
)
filter = Filter(filter)
filter.settimezone(None)
results = yield toCalendar.search(filter, 'user01', True)
self.assertEquals(len(results), 1)
_ignore_name, uid, _ignore_type, _ignore_organizer, _ignore_float, _ignore_start, _ignore_end, _ignore_fbtype, transp = results[0]
self.assertEquals(uid, "uid4")
self.assertEquals(transp, 'T')
@inlineCallbacks
def test_migrateHomeFromFile(self):
"""
L{migrateHome} will migrate an L{ICalendarHome} provider from one
backend to another; in this specific case, from the file-based backend
to the SQL-based backend.
"""
# Need to turn of split calendar behavior just for this test
self.patch(config, "RestrictCalendarsToOneComponentType", False)
fromHome = yield self.fileTransaction().calendarHomeWithUID("home1")
builtinProperties = [PropertyName.fromElement(ResourceType)]
# Populate an arbitrary / unused dead properties so there's something
# to verify against.
key = PropertyName.fromElement(GETContentLanguage)
fromHome.properties()[key] = GETContentLanguage("C")
(yield fromHome.calendarWithName("calendar_1")).properties()[key] = (
GETContentLanguage("pig-latin")
)
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True
)
yield migrateHome(fromHome, toHome, lambda x: x.component())
toCalendars = yield toHome.calendars()
self.assertEquals(set([c.name() for c in toCalendars if c.name() not in ("inbox",)]),
set([k for k in self.requirements['home1'].keys()
if self.requirements['home1'][k] is not None]))
fromCalendars = yield fromHome.calendars()
for c in fromCalendars:
self.assertPropertiesSimilar(
c, (yield toHome.calendarWithName(c.name())),
builtinProperties
)
self.assertPropertiesSimilar(fromHome, toHome, builtinProperties)
@inlineCallbacks
def test_migrateHomeSplits(self):
"""
Make sure L{migrateHome} also splits calendars by component type.
"""
fromHome = yield self.fileTransaction().calendarHomeWithUID("home_splits")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True
)
yield migrateHome(fromHome, toHome, lambda x: x.component())
toCalendars = yield toHome.calendars()
fromCalendars = yield fromHome.calendars()
for c in fromCalendars:
self.assertTrue(
(yield toHome.calendarWithName(c.name())) is not None
)
supported_components = set()
self.assertEqual(len(toCalendars), 2 + len(ical.allowedStoreComponents))
for calendar in toCalendars:
if calendar.name() in ("inbox",):
continue
result = yield calendar.getSupportedComponents()
supported_components.add(result)
self.assertEqual(supported_components, set(ical.allowedStoreComponents))
@inlineCallbacks
def test_migrateHomeNoSplits(self):
"""
Make sure L{migrateHome} also splits calendars by component type.
"""
fromHome = yield self.fileTransaction().calendarHomeWithUID("home_no_splits")
toHome = yield self.transactionUnderTest().calendarHomeWithUID(
"new-home", create=True
)
yield migrateHome(fromHome, toHome, lambda x: x.component())
toCalendars = yield toHome.calendars()
fromCalendars = yield fromHome.calendars()
for c in fromCalendars:
self.assertTrue(
(yield toHome.calendarWithName(c.name())) is not None
)
supported_components = set()
self.assertEqual(len(toCalendars), 3)
for calendar in toCalendars:
if calendar.name() in ("inbox",):
continue
result = yield calendar.getSupportedComponents()
supported_components.add(result)
self.assertEqual(supported_components, set(ical.allowedStoreComponents))
@inlineCallbacks
def test_calendarHomeVersion(self):
"""
The DATAVERSION column for new calendar homes must match the
CALENDAR-DATAVERSION value.
"""
self.transactionUnderTest()._homeClass[ECALENDARTYPE]._dataVersionValue = None
home = yield self.transactionUnderTest().calendarHomeWithUID("home_version", create=True)
self.assertTrue(home is not None)
yield self.transactionUnderTest().commit
txn = yield self.transactionUnderTest()
version = yield txn.calendarserverValue("CALENDAR-DATAVERSION")
ch = schema.CALENDAR_HOME
homeVersion = (yield Select(
[ch.DATAVERSION, ],
From=ch,
Where=ch.OWNER_UID == "home_version",
).on(txn))[0][0]
self.assertEqual(int(homeVersion), int(version))
@inlineCallbacks
def test_homeProvisioningConcurrency(self):
"""
Test that two concurrent attempts to provision a calendar home do not
cause a race-condition whereby the second commit results in a second
C{INSERT} that violates a unique constraint. Also verify that, while
the two provisioning attempts are happening and doing various lock
operations, that we do not block other reads of the table.
"""
calendarStore = self._sqlCalendarStore
txn1 = calendarStore.newTransaction()
txn2 = calendarStore.newTransaction()
txn3 = calendarStore.newTransaction()
# Provision one home now - we will use this to later verify we can do
# reads of existing data in the table
home_uid2 = yield txn3.homeWithUID(ECALENDARTYPE, "uid2", create=True)
self.assertNotEqual(home_uid2, None)
yield txn3.commit()
home_uid1_1 = yield txn1.homeWithUID(
ECALENDARTYPE, "uid1", create=True
)
@inlineCallbacks
def _defer_home_uid1_2():
home_uid1_2 = yield txn2.homeWithUID(
ECALENDARTYPE, "uid1", create=True
)
yield txn2.commit()
returnValue(home_uid1_2)
d1 = _defer_home_uid1_2()
@inlineCallbacks
def _pause_home_uid1_1():
yield deferLater(reactor, 1.0, lambda : None)
yield txn1.commit()
d2 = _pause_home_uid1_1()
# Verify that we can still get to the existing home - i.e. the lock
# on the table allows concurrent reads
txn4 = calendarStore.newTransaction()
home_uid2 = yield txn4.homeWithUID(ECALENDARTYPE, "uid2", create=True)
self.assertNotEqual(home_uid2, None)
yield txn4.commit()
# Now do the concurrent provision attempt
yield d2
home_uid1_2 = yield d1
self.assertNotEqual(home_uid1_1, None)
self.assertNotEqual(home_uid1_2, None)
@inlineCallbacks
def test_putConcurrency(self):
"""
Test that two concurrent attempts to PUT different calendar object
resources to the same calendar home does not cause a deadlock.
"""
calendarStore = self._sqlCalendarStore
# Provision the home and calendar now
txn = calendarStore.newTransaction()
home = yield txn.homeWithUID(ECALENDARTYPE, "user01", create=True)
self.assertNotEqual(home, None)
cal = yield home.calendarWithName("calendar")
self.assertNotEqual(cal, None)
yield txn.commit()
txn1 = calendarStore.newTransaction()
txn2 = calendarStore.newTransaction()
home1 = yield txn1.homeWithUID(ECALENDARTYPE, "user01", create=True)
home2 = yield txn2.homeWithUID(ECALENDARTYPE, "user01", create=True)
cal1 = yield home1.calendarWithName("calendar")
cal2 = yield home2.calendarWithName("calendar")
@inlineCallbacks
def _defer1():
yield cal1.createObjectResourceWithName("1.ics", Component.fromString("""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:US/Pacific
BEGIN:DAYLIGHT
TZOFFSETFROM:-0800
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
DTSTART:20070311T020000
TZNAME:PDT
TZOFFSETTO:-0700
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0700
RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
DTSTART:20071104T020000
TZNAME:PST
TZOFFSETTO:-0800
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
CREATED:20100203T013849Z
UID:uid1
DTEND;TZID=US/Pacific:%(now)s0207T173000
TRANSP:OPAQUE
SUMMARY:New Event
DTSTART;TZID=US/Pacific:%(now)s0207T170000
DTSTAMP:20100203T013909Z
SEQUENCE:3
BEGIN:VALARM
X-WR-ALARMUID:1377CCC7-F85C-4610-8583-9513D4B364E1
TRIGGER:-PT20M
ATTACH;VALUE=URI:Basso
ACTION:AUDIO
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n") % self.nowYear
))
yield txn1.commit()
d1 = _defer1()
@inlineCallbacks
def _defer2():
yield cal2.createObjectResourceWithName("2.ics", Component.fromString("""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:US/Pacific
BEGIN:DAYLIGHT
TZOFFSETFROM:-0800
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
DTSTART:20070311T020000
TZNAME:PDT
TZOFFSETTO:-0700
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0700
RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
DTSTART:20071104T020000
TZNAME:PST
TZOFFSETTO:-0800
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
CREATED:20100203T013849Z
UID:uid2
DTEND;TZID=US/Pacific:%(now)s0207T173000
TRANSP:OPAQUE
SUMMARY:New Event
DTSTART;TZID=US/Pacific:%(now)s0207T170000
DTSTAMP:20100203T013909Z
SEQUENCE:3
BEGIN:VALARM
X-WR-ALARMUID:1377CCC7-F85C-4610-8583-9513D4B364E1
TRIGGER:-PT20M
ATTACH;VALUE=URI:Basso
ACTION:AUDIO
END:VALARM
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n") % self.nowYear
))
yield txn2.commit()
d2 = _defer2()
yield d1
yield d2
@inlineCallbacks
def test_datetimes(self):
calendarStore = self._sqlCalendarStore
# Provision the home and calendar now
txn = calendarStore.newTransaction()
home = yield txn.homeWithUID(ECALENDARTYPE, "uid1", create=True)
cal = yield home.calendarWithName("calendar")
cal._created = parseSQLTimestamp("2011-02-05 11:22:47")
cal._modified = parseSQLTimestamp("2011-02-06 11:22:47")
self.assertEqual(cal.created(), datetimeMktime(datetime.datetime(2011, 2, 5, 11, 22, 47)))
self.assertEqual(cal.modified(), datetimeMktime(datetime.datetime(2011, 2, 6, 11, 22, 47)))
obj = yield self.calendarObjectUnderTest()
obj._created = parseSQLTimestamp("2011-02-07 11:22:47")
obj._modified = parseSQLTimestamp("2011-02-08 11:22:47")
self.assertEqual(obj.created(), datetimeMktime(datetime.datetime(2011, 2, 7, 11, 22, 47)))
self.assertEqual(obj.modified(), datetimeMktime(datetime.datetime(2011, 2, 8, 11, 22, 47)))
@inlineCallbacks
def test_notificationsProvisioningConcurrency(self):
"""
Test that two concurrent attempts to provision a notifications collection do not
cause a race-condition whereby the second commit results in a second
C{INSERT} that violates a unique constraint.
"""
calendarStore = self._sqlCalendarStore
txn1 = calendarStore.newTransaction()
txn2 = calendarStore.newTransaction()
notification_uid1_1 = yield txn1.notificationsWithUID(
"uid1", create=True
)
@inlineCallbacks
def _defer_notification_uid1_2():
notification_uid1_2 = yield txn2.notificationsWithUID(
"uid1", create=True
)
yield txn2.commit()
returnValue(notification_uid1_2)
d1 = _defer_notification_uid1_2()
@inlineCallbacks
def _pause_notification_uid1_1():
yield deferLater(reactor, 1.0, lambda : None)
yield txn1.commit()
d2 = _pause_notification_uid1_1()
# Now do the concurrent provision attempt
yield d2
notification_uid1_2 = yield d1
self.assertNotEqual(notification_uid1_1, None)
self.assertNotEqual(notification_uid1_2, None)
@inlineCallbacks
def test_removeCalendarPropertiesOnDelete(self):
"""
L{ICalendarHome.removeCalendarWithName} removes a calendar that already
exists and makes sure properties are also removed.
"""
# Create calendar and add a property
home = yield self.homeUnderTest()
name = "remove-me"
calendar = yield home.createCalendarWithName(name)
resourceID = calendar._resourceID
calendarProperties = calendar.properties()
prop = caldavxml.CalendarDescription.fromString("Calendar to be removed")
calendarProperties[PropertyName.fromElement(prop)] = prop
yield self.commit()
prop = schema.RESOURCE_PROPERTY
_allWithID = Select(
[prop.NAME, prop.VIEWER_UID, prop.VALUE],
From=prop,
Where=prop.RESOURCE_ID == Parameter("resourceID")
)
# Check that one property is present
home = yield self.homeUnderTest()
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 1)
yield self.commit()
# Remove calendar and check for no properties
home = yield self.homeUnderTest()
yield home.removeCalendarWithName(name, useTrash=False)
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
# Recheck it
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
@inlineCallbacks
def test_removeCalendarObjectPropertiesOnDelete(self):
"""
L{ICalendarHome.removeCalendarWithName} removes a calendar object that already
exists and makes sure properties are also removed (which is always the case as right
now calendar objects never have properties).
"""
# Create calendar object
calendar1 = yield self.calendarUnderTest()
name = "test.ics"
component = Component.fromString(test_event_text)
metadata = {
"accessMode": "PUBLIC",
"isScheduleObject": True,
"scheduleTag": "abc",
"scheduleEtags": (),
"hasPrivateComment": False,
}
calobject = yield calendar1.createCalendarObjectWithName(name, component, options=metadata)
resourceID = calobject._resourceID
prop = schema.RESOURCE_PROPERTY
_allWithID = Select(
[prop.NAME, prop.VIEWER_UID, prop.VALUE],
From=prop,
Where=prop.RESOURCE_ID == Parameter("resourceID")
)
# No properties on existing calendar object
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
# Remove calendar and check for no properties
calendar1 = yield self.calendarUnderTest()
obj1 = yield calendar1.calendarObjectWithName(name)
yield obj1.remove()
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
# Recheck it
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
@inlineCallbacks
def test_removeInboxObjectPropertiesOnDelete(self):
"""
L{ICalendarHome.removeCalendarWithName} removes an inbox calendar object that already
exists and makes sure properties are also removed. Inbox calendar objects can have properties.
"""
# Create calendar object and add a property
home = yield self.homeUnderTest()
inbox = yield home.createCalendarWithName("inbox")
name = "test.ics"
component = Component.fromString(test_event_text)
metadata = {
"accessMode": "PUBLIC",
"isScheduleObject": True,
"scheduleTag": "abc",
"scheduleEtags": (),
"hasPrivateComment": False,
}
calobject = yield inbox.createCalendarObjectWithName(name, component, options=metadata)
resourceID = calobject._resourceID
calobjectProperties = calobject.properties()
prop = caldavxml.CalendarDescription.fromString("Calendar object to be removed")
calobjectProperties[PropertyName.fromElement(prop)] = prop
yield self.commit()
prop = schema.RESOURCE_PROPERTY
_allWithID = Select(
[prop.NAME, prop.VIEWER_UID, prop.VALUE],
From=prop,
Where=prop.RESOURCE_ID == Parameter("resourceID")
)
# One property exists calendar object
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 1)
yield self.commit()
# Remove calendar object and check for no properties
home = yield self.homeUnderTest()
inbox = yield home.calendarWithName("inbox")
obj1 = yield inbox.calendarObjectWithName(name)
yield obj1.remove()
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
# Recheck it
rows = yield _allWithID.on(self.transactionUnderTest(), resourceID=resourceID)
self.assertEqual(len(tuple(rows)), 0)
yield self.commit()
@inlineCallbacks
def test_removeNotifyCategoryInbox(self):
"""
Inbox object removal should be categorized as ChangeCategory.inbox
"""
home = yield self.homeUnderTest()
inbox = yield home.createCalendarWithName("inbox")
component = Component.fromString(test_event_text)
inboxItem = yield inbox.createCalendarObjectWithName("inbox.ics", component)
self.assertEquals(ChangeCategory.inbox, inboxItem.removeNotifyCategory())
yield self.commit()
@inlineCallbacks
def test_removeNotifyCategoryNonInbox(self):
"""
Non-Inbox object removal should be categorized as ChangeCategory.default
"""
home = yield self.homeUnderTest()
nonInbox = yield home.createCalendarWithName("noninbox")
component = Component.fromString(test_event_text)
nonInboxItem = yield nonInbox.createCalendarObjectWithName("inbox.ics", component)
self.assertEquals(ChangeCategory.default, nonInboxItem.removeNotifyCategory())
yield self.commit()
@inlineCallbacks
def test_directShareCreateConcurrency(self):
"""
Test that two concurrent attempts to create a direct shared calendar
work concurrently without an exception.
"""
calendarStore = self._sqlCalendarStore
# Provision the home and calendar now
txn = calendarStore.newTransaction()
sharerHome = yield txn.homeWithUID(ECALENDARTYPE, "uid1", create=True)
self.assertNotEqual(sharerHome, None)
cal = yield sharerHome.calendarWithName("calendar")
self.assertNotEqual(cal, None)
shareeHome = yield txn.homeWithUID(ECALENDARTYPE, "uid2", create=True)
self.assertNotEqual(shareeHome, None)
yield txn.commit()
txn1 = calendarStore.newTransaction()
txn2 = calendarStore.newTransaction()
sharerHome1 = yield txn1.homeWithUID(ECALENDARTYPE, "uid1", create=True)
self.assertNotEqual(sharerHome1, None)
cal1 = yield sharerHome1.calendarWithName("calendar")
self.assertNotEqual(cal1, None)
shareeHome1 = yield txn1.homeWithUID(ECALENDARTYPE, "uid2", create=True)