-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathtest_caldav.py
More file actions
2915 lines (2577 loc) · 108 KB
/
test_caldav.py
File metadata and controls
2915 lines (2577 loc) · 108 KB
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Tests here communicate with third party servers and/or
internal ad-hoc instances of Xandikos and Radicale, dependent on the
configuration in conf_private.py.
Tests that do not require communication with a working caldav server
belong in test_caldav_unit.py
"""
import codecs
import logging
import random
import sys
import threading
import time
import uuid
from collections import namedtuple
from datetime import date
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from urllib.parse import urlparse
import icalendar
import pytest
import vobject
from . import compatibility_issues
from .conf import caldav_servers
from .conf import client
from .conf import proxy
from .conf import proxy_noport
from .conf import radicale_host
from .conf import radicale_port
from .conf import rfc6638_users
from .conf import test_radicale
from .conf import test_xandikos
from .conf import xandikos_host
from .conf import xandikos_port
from .proxy import NonThreadingHTTPServer
from .proxy import ProxyHandler
from caldav.davclient import DAVClient
from caldav.davclient import DAVResponse
from caldav.elements import cdav
from caldav.elements import dav
from caldav.elements import ical
from caldav.lib import error
from caldav.lib import url
from caldav.lib.python_utilities import to_local
from caldav.lib.python_utilities import to_str
from caldav.lib.url import URL
from caldav.objects import Calendar
from caldav.objects import CalendarSet
from caldav.objects import DAVObject
from caldav.objects import Event
from caldav.objects import FreeBusy
from caldav.objects import Principal
from caldav.objects import Todo
log = logging.getLogger("caldav")
ev1 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:20010712T182145Z-123401@example.com
DTSTAMP:20060712T182145Z
DTSTART:20060714T170000Z
DTEND:20060715T040000Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR
"""
broken_ev1 = """BEGIN:VEVENT
UID:20010712T182145Z-123401@example.com
DTSTART:20060714T170000Z
DTEND:20060715T040000Z
SUMMARY:Bastille Day Party
END:VEVENT
"""
ev2 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:20010712T182145Z-123401@example.com
DTSTAMP:20070712T182145Z
DTSTART:20070714T170000Z
DTEND:20070715T040000Z
SUMMARY:Bastille Day Party +1year
END:VEVENT
END:VCALENDAR
"""
ev3 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:20080712T182145Z-123401@example.com
DTSTAMP:20210712T182145Z
DTSTART:20210714T170000Z
DTEND:20210715T040000Z
SUMMARY:Bastille Day Jitsi Party
END:VEVENT
END:VCALENDAR
"""
## This list is for deleting the events/todo-items in case it isn't
## sufficient/possible to create/delete the whole test calendar.
uids_used = (
"19920901T130000Z-123407@host.com",
"19920901T130000Z-123408@host.com",
"19970901T130000Z-123403@example.com",
"19970901T130000Z-123404@host.com",
"19970901T130000Z-123405@example.com",
"19970901T130000Z-123405@host.com",
"19970901T130000Z-123406@host.com",
"20010712T182145Z-123401@example.com",
"20070313T123432Z-456553@example.com",
"20080712T182145Z-123401@example.com",
"19970901T130000Z-123403@example.com",
"20010712T182145Z-123401@example.com",
"20080712T182145Z-123401@example.com",
"takeoutthethrash",
"ctuid1",
"ctuid2",
"ctuid3",
"ctuid4",
"ctuid5",
"ctuid6",
"test1",
"test2",
"test3",
"test4",
"test5",
"test6",
)
## TODO: todo7 is an item without uid. Should be taken care of somehow.
# example from http://www.rfc-editor.org/rfc/rfc5545.txt
evr = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:19970901T130000Z-123403@example.com
DTSTAMP:19970901T130000Z
DTSTART;VALUE=DATE:19971102
SUMMARY:Our Blissful Anniversary
TRANSP:TRANSPARENT
CLASS:CONFIDENTIAL
CATEGORIES:ANNIVERSARY,PERSONAL,SPECIAL OCCASION
RRULE:FREQ=YEARLY
END:VEVENT
END:VCALENDAR"""
# example created by editing a specific occurrence of a recurrent event via Thunderbird
evr2 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN
BEGIN:VEVENT
UID:c26921f4-0653-11ef-b756-58ce2a14e2e5
DTSTART:20240411T123000Z
DTEND:20240412T123000Z
DTSTAMP:20240429T181103Z
LAST-MODIFIED:20240429T181103Z
RRULE:FREQ=WEEKLY;INTERVAL=2
SEQUENCE:1
SUMMARY:Test
X-MOZ-GENERATION:1
END:VEVENT
BEGIN:VEVENT
UID:c26921f4-0653-11ef-b756-58ce2a14e2e5
RECURRENCE-ID:20240425T123000Z
DTSTART:20240425T123000Z
DTEND:20240426T123000Z
CREATED:20240429T181031Z
DTSTAMP:20240429T181103Z
LAST-MODIFIED:20240429T181103Z
SEQUENCE:1
SUMMARY:Test (edited)
X-MOZ-GENERATION:1
END:VEVENT
END:VCALENDAR"""
# example from http://www.rfc-editor.org/rfc/rfc5545.txt
todo = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:20070313T123432Z-456553@example.com
DTSTAMP:20070313T123432Z
DUE;VALUE=DATE:20070501
SUMMARY:Submit Quebec Income Tax Return for 2006
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR"""
# example from RFC2445, 4.6.2
todo2 = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19970901T130000Z-123404@host.com
DTSTAMP:19970901T130000Z
DTSTART:19970415T133000Z
DUE:19970416T045959Z
SUMMARY:1996 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:2
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR"""
todo3 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19970901T130000Z-123405@host.com
DTSTAMP:19970901T130000Z
DTSTART:19970415T133000Z
DUE:19970516T045959Z
SUMMARY:1996 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:1
END:VTODO
END:VCALENDAR"""
todo4 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19970901T130000Z-123406@host.com
DTSTAMP:19970901T130000Z
SUMMARY:1996 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:1
STATUS:NEEDS-ACTION
END:VTODO
END:VCALENDAR"""
todo5 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19920901T130000Z-123407@host.com
DTSTAMP:19920901T130000Z
DTSTART:19920415T133000Z
DUE:19920516T045959Z
SUMMARY:1992 Income Tax Preparation
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:1
END:VTODO
END:VCALENDAR"""
todo6 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:19920901T130000Z-123408@host.com
DTSTAMP:19920901T130000Z
DTSTART:19920415T133000Z
DUE:19920516T045959Z
SUMMARY:Yearly Income Tax Preparation
RRULE:FREQ=YEARLY
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY,FINANCE
PRIORITY:1
END:VTODO
END:VCALENDAR"""
## a todo without uid. Should it be possible to store it at all?
todo7 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
DTSTAMP:19980101T130000Z
DTSTART:19980415T133000Z
DUE:19980516T045959Z
STATUS:NEEDS-ACTION
SUMMARY:Get stuck with Netfix and forget about the tax income declaration
CLASS:CONFIDENTIAL
CATEGORIES:FAMILY
PRIORITY:1
END:VTODO
END:VCALENDAR"""
todo8 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTODO
UID:takeoutthethrash
DTSTAMP:20221013T151313Z
DTSTART:20221017T065500Z
STATUS:NEEDS-ACTION
DURATION:PT10M
SUMMARY:Take out the thrash before the collectors come.
RRULE:FREQ=WEEKLY;BYDAY=MO;BYHOUR=6;BYMINUTE=55;COUNT=3
CATEGORIES:CHORE
PRIORITY:3
END:VTODO
END:VCALENDAR"""
# example from http://www.kanzaki.com/docs/ical/vjournal.html
journal = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VJOURNAL
UID:19970901T130000Z-123405@example.com
DTSTAMP:19970901T130000Z
DTSTART;VALUE=DATE:19970317
SUMMARY:Staff meeting minutes
DESCRIPTION:1. Staff meeting: Participants include Joe\\, Lisa
and Bob. Aurora project plans were reviewed. There is currently
no budget reserves for this project. Lisa will escalate to
management. Next meeting on Tuesday.\n
END:VJOURNAL
END:VCALENDAR
"""
## From RFC4438 examples, with some modifications
sched_template = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:%s
SEQUENCE:0
DTSTAMP:20210206T%sZ
DTSTART:203206%02iT%sZ
DURATION:PT1H
TRANSP:OPAQUE
SUMMARY:Lunch or something
END:VEVENT
END:VCALENDAR
"""
attendee1 = """
BEGIN:VCALENDAR
PRODID:-//Example Corp.//CalDAV Client//EN
VERSION:2.0
BEGIN:VEVENT
STATUS:CANCELLED
UID:test-attendee1
X-MICROSOFT-DISALLOW-COUNTER:true
DTSTART;TZID=Europe/Moscow:20240607T100000
DTEND;TZID=Europe/Moscow:20240607T103000
LAST-MODIFIED:20240610T063933Z
DTSTAMP:20240618T063824Z
CREATED:00010101T000000Z
SUMMARY:test
SEQUENCE:0
TRANSP:OPAQUE
X-MOZ-LASTACK:20240610T063933Z
ORGANIZER;CN=:mailto:t-caldav-test-att1@tobixen.no
ATTENDEE;PARTSTAT=ACCEPTED;RSVP=true;ROLE=REQ-PARTICIPANT:mailto:t-test-attendee1@tobixen.no
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=DECLINED:mailto:testemail2024@list.ru
END:VEVENT
BEGIN:VTIMEZONE
TZID:Europe/Moscow
TZURL:http://tzurl.org/zoneinfo-outlook/Europe/Moscow
X-LIC-LOCATION:Europe/Moscow
BEGIN:STANDARD
TZNAME:MSK
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
DTSTART:19700101T000000
END:STANDARD
END:VTIMEZONE
END:VCALENDAR
"""
attendee2 = """
BEGIN:VCALENDAR
PRODID:-//MailRu//MailRu Calendar API -//EN
VERSION:2.0
BEGIN:VEVENT
STATUS:CANCELLED
UID:EB424921-C4D3-46A6-B827-9A92A90D6788
X-MICROSOFT-DISALLOW-COUNTER:true
DTSTART;TZID=Europe/Moscow:20240607T100000
DTEND;TZID=Europe/Moscow:20240607T103000
LAST-MODIFIED:20240610T063933Z
DTSTAMP:20240618T064033Z
CREATED:00010101T000000Z
SUMMARY:test
SEQUENCE:0
TRANSP:OPAQUE
X-MOZ-LASTACK:20240610T063933Z
ORGANIZER;CN=:mailto:knazarov@i-core.ru
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=true:mailto:knazarov@i
-core.ru
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=DECLINED:mailto:testemail2024@list.r
u
END:VEVENT
BEGIN:VTIMEZONE
TZID:Europe/Moscow
TZURL:http://tzurl.org/zoneinfo-outlook/Europe/Moscow
X-LIC-LOCATION:Europe/Moscow
BEGIN:STANDARD
TZNAME:MSK
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
DTSTART:19700101T000000
END:STANDARD
END:VTIMEZONE
END:VCALENDAR
"""
sched = sched_template % (
str(uuid.uuid4()),
"%2i%2i%2i" % (random.randint(0, 23), random.randint(0, 59), random.randint(0, 59)),
random.randint(1, 28),
"%2i%2i%2i" % (random.randint(0, 23), random.randint(0, 59), random.randint(0, 59)),
)
@pytest.mark.skipif(
not rfc6638_users, reason="need rfc6638_users to be set in order to run this test"
)
@pytest.mark.skipif(
len(rfc6638_users) < 3,
reason="need at least three users in rfc6638_users to be set in order to run this test",
)
class TestScheduling:
"""Testing support of RFC6638.
TODO: work in progress. Stalled a bit due to lack of proper testing accounts. I haven't managed to get this test to pass at any systems yet, but I believe the problem is not on the library side.
* icloud: cannot really test much with only one test account
available. I did some testing forth and back with emails sent
to an account on another service through the
scheduling_examples.py, and it seems like I was able both to
accept an invite from an external account (and the external
account got notified about it) and to receive notification that
the external party having accepted the calendar invite.
FreeBusy doesn't work. I don't have capacity following up more
right now.
* DAViCal: I have only an old version to test with at the moment,
should look into that. I did manage to send and receive a
calendar invite, but apparently I did not manage to accept the
calendar invite. It should be looked more into. FreeBusy
doesn't work in the old version, probably it works in a newer
version.
* SOGo: Sending a calendar invite, but receiving nothing in the
CalDAV inbox. FreeBusy works somehow, but returns pure
iCalendar data and not XML, I believe that's not according to
RFC6638.
"""
def _getCalendar(self, i):
calendar_id = "schedulingnosetestcalendar%i" % i
calendar_name = "caldav scheduling test %i" % i
try:
self.principals[i].calendar(name=calendar_name).delete()
except error.NotFoundError:
pass
return self.principals[i].make_calendar(name=calendar_name, cal_id=calendar_id)
def setup_method(self):
self.clients = []
self.principals = []
for foo in rfc6638_users:
c = client(**foo)
if not c.check_scheduling_support():
continue ## ignoring user because server does not support scheduling.
self.clients.append(c)
self.principals.append(c.principal())
def teardown_method(self):
for i in range(0, len(self.principals)):
calendar_name = "caldav scheduling test %i" % i
try:
self.principals[i].calendar(name=calendar_name).delete()
except error.NotFoundError:
pass
for c in self.clients:
c.teardown()
## TODO
# def testFreeBusy(self):
# pass
def testInviteAndRespond(self):
## Look through inboxes of principals[0] and principals[1] so we can sort
## out existing stuff from new stuff
if len(self.principals) < 2:
pytest.skip("need 2 principals to do the invite and respond test")
inbox_items = set(
[x.url for x in self.principals[0].schedule_inbox().get_items()]
)
inbox_items.update(
set([x.url for x in self.principals[1].schedule_inbox().get_items()])
)
## self.principal[0] is the organizer, and invites self.principal[1]
organizers_calendar = self._getCalendar(0)
attendee_calendar = self._getCalendar(1)
organizers_calendar.save_with_invites(
sched, [self.principals[0], self.principals[1].get_vcal_address()]
)
assert len(organizers_calendar.events()) == 1
## no new inbox items expected for principals[0]
for item in self.principals[0].schedule_inbox().get_items():
assert item.url in inbox_items
## principals[1] should have one new inbox item
new_inbox_items = []
for item in self.principals[1].schedule_inbox().get_items():
if not item.url in inbox_items:
new_inbox_items.append(item)
assert len(new_inbox_items) == 1
## ... and the new inbox item should be an invite request
assert new_inbox_items[0].is_invite_request()
## Approving the invite
new_inbox_items[0].accept_invite(calendar=attendee_calendar)
## (now, this item should probably appear on a calendar somewhere ...
## TODO: make asserts on that)
## TODO: what happens if we delete that invite request now?
## principals[0] should now have a notification in the inbox that the
## calendar invite was accepted
new_inbox_items = []
for item in self.principals[0].schedule_inbox().get_items():
if not item.url in inbox_items:
new_inbox_items.append(item)
assert len(new_inbox_items) == 1
assert new_inbox_items[0].is_invite_reply()
new_inbox_items[0].delete()
## TODO. Invite two principals, let both of them load the
## invitation, and then let them respond in order. Lacks both
## tests and the implementation also apparently doesn't work as
## for now (perhaps I misunderstood the RFC).
# def testAcceptedInviteRaceCondition(self):
# pass
## TODO: more testing ... what happens if deleting things from the
## inbox/outbox?
def _delay_decorator(f, t=60):
def foo(*a, **kwa):
time.sleep(t)
return f(*a, **kwa)
return foo
class RepeatedFunctionalTestsBaseClass:
"""This is a class with functional tests (tests that goes through
basic functionality and actively communicates with third parties)
that we want to repeat for all configured caldav_servers.
(what a truly ugly name for this class - any better ideas?)
NOTE: this tests relies heavily on the assumption that we can create
calendars on the remote caldav server, but the RFC says ...
Support for MKCALENDAR on the server is only RECOMMENDED and not
REQUIRED because some calendar stores only support one calendar per
user (or principal), and those are typically pre-created for each
account.
We've had some problems with iCloud and Radicale earlier. Google
still does not support mkcalendar.
"""
_default_calendar = None
def check_compatibility_flag(self, flag):
## yield an assertion error if checking for the wrong thig
assert flag in compatibility_issues.incompatibility_description
return flag in self.incompatibilities
def skip_on_compatibility_flag(self, flag):
if self.check_compatibility_flag(flag):
msg = compatibility_issues.incompatibility_description[flag]
pytest.skip("Test skipped due to server incompatibility issue: " + msg)
def setup_method(self):
logging.debug("############## test setup")
self.incompatibilities = set()
self.cleanup_regime = self.server_params.get("cleanup", "light")
self.calendars_used = []
for flag in self.server_params.get("incompatibilities", []):
assert flag in compatibility_issues.incompatibility_description
self.incompatibilities.add(flag)
if self.check_compatibility_flag("unique_calendar_ids"):
self.testcal_id = "testcalendar-" + str(uuid.uuid4())
self.testcal_id2 = "testcalendar-" + str(uuid.uuid4())
else:
self.testcal_id = "pythoncaldav-test"
self.testcal_id2 = "pythoncaldav-test2"
self.caldav = client(**self.server_params)
if self.check_compatibility_flag("rate_limited"):
self.caldav.request = _delay_decorator(self.caldav.request)
if self.check_compatibility_flag("search_delay"):
Calendar._search = Calendar.search
Calendar.search = _delay_decorator(Calendar.search)
if False and self.check_compatibility_flag("no-current-user-principal"):
self.principal = Principal(
client=self.caldav, url=self.server_params["principal_url"]
)
else:
self.principal = self.caldav.principal()
# if self.check_compatibility_flag('delete_calendar_on_startup'):
# for x in self._fixCalendar().search():
# x.delete()
self._cleanup("pre")
logging.debug("##############################")
logging.debug("############## test setup done")
logging.debug("##############################")
def teardown_method(self):
if self.check_compatibility_flag("search_delay"):
Calendar.search = Calendar._search
logging.debug("############################")
logging.debug("############## test teardown_method")
logging.debug("############################")
self._cleanup("post")
logging.debug("############## test teardown_method almost done")
self.caldav.teardown(self.caldav)
def _cleanup(self, mode=None):
if self.cleanup_regime in ("pre", "post") and self.cleanup_regime != mode:
return
if self.check_compatibility_flag("read_only"):
return ## no cleanup needed
if (
self.check_compatibility_flag("no_mkcalendar")
or self.cleanup_regime == "thorough"
):
for uid in uids_used:
try:
obj = self._fixCalendar().object_by_uid(uid)
obj.delete()
except error.NotFoundError:
pass
except:
logging.error(
"Something went kaboom while deleting event", exc_info=True
)
return
for cal in self.calendars_used:
cal.delete()
if self.check_compatibility_flag("unique_calendar_ids") and mode == "pre":
a = self._teardownCalendar(name="Yep")
if mode == "post":
for calid in (self.testcal_id, self.testcal_id2):
self._teardownCalendar(cal_id=calid)
if self.cleanup_regime == "thorough":
for name in ("Yep", "Yapp", "Yølp", self.testcal_id, self.testcal_id2):
self._teardownCalendar(name=name)
self._teardownCalendar(cal_id=name)
def _teardownCalendar(self, name=None, cal_id=None):
try:
cal = self.principal.calendar(name=name, cal_id=cal_id)
if self.check_compatibility_flag(
"sticky_events"
) or self.check_compatibility_flag("no_delete_calendar"):
for goo in cal.objects():
try:
goo.delete()
except:
pass
cal.delete()
except:
pass
def _fixCalendar(self, **kwargs):
"""
Should ideally return a new calendar, if that's not possible it
should see if there exists a test calendar, if that's not
possible, give up and return the primary calendar.
"""
if self.check_compatibility_flag(
"no_mkcalendar"
) or self.check_compatibility_flag("read_only"):
if not self._default_calendar:
calendars = self.principal.calendars()
for c in calendars:
if (
"pythoncaldav-test"
in c.get_properties(
[
dav.DisplayName(),
]
).values()
):
self._default_calendar = c
return c
self._default_calendar = calendars[0]
return self._default_calendar
else:
if not "name" in kwargs:
if not self.check_compatibility_flag(
"unique_calendar_ids"
) and self.cleanup_regime in ("light", "pre"):
self._teardownCalendar(cal_id=self.testcal_id)
if self.check_compatibility_flag("no_displayname"):
kwargs["name"] = None
else:
kwargs["name"] = "Yep"
if not "cal_id" in kwargs:
kwargs["cal_id"] = self.testcal_id
try:
ret = self.principal.make_calendar(**kwargs)
except error.MkcalendarError:
## "calendar already exists" can be ignored (at least
## if no_delete_calendar flag is set)
ret = self.principal.calendar(cal_id=kwargs["cal_id"])
if self.check_compatibility_flag("search_always_needs_comptype"):
ret.objects = lambda load_objects: ret.events()
if self.cleanup_regime == "post":
self.calendars_used.append(ret)
return ret
def testSupport(self):
"""
Test the check_*_support methods
"""
self.skip_on_compatibility_flag("dav_not_supported")
assert self.caldav.check_dav_support()
assert self.caldav.check_cdav_support()
if self.check_compatibility_flag("no_scheduling"):
assert not self.caldav.check_scheduling_support()
else:
assert self.caldav.check_scheduling_support()
def testSchedulingInfo(self):
self.skip_on_compatibility_flag("no_scheduling")
calendar_user_address_set = self.principal.calendar_user_address_set()
me_a_participant = self.principal.get_vcal_address()
def testSchedulingMailboxes(self):
self.skip_on_compatibility_flag("no_scheduling")
self.skip_on_compatibility_flag("no_scheduling_mailbox")
inbox = self.principal.schedule_inbox()
outbox = self.principal.schedule_outbox()
def testPropfind(self):
"""
Test of the propfind methods. (This is sort of redundant, since
this is implicitly run by the setup)
"""
# ResourceType MUST be defined, and SHOULD be returned on a propfind
# for "allprop" if I have the permission to see it.
# So, no ResourceType returned seems like a bug in bedework
self.skip_on_compatibility_flag("propfind_allprop_failure")
# first a raw xml propfind to the root URL
foo = self.caldav.propfind(
self.principal.url,
props='<?xml version="1.0" encoding="UTF-8"?>'
'<D:propfind xmlns:D="DAV:">'
" <D:allprop/>"
"</D:propfind>",
)
assert "resourcetype" in to_local(foo.raw)
# next, the internal _query_properties, returning an xml tree ...
foo2 = self.principal._query_properties(
[
dav.Status(),
]
)
assert "resourcetype" in to_local(foo.raw)
# TODO: more advanced asserts
def testGetCalendarHomeSet(self):
chs = self.principal.get_properties([cdav.CalendarHomeSet()])
assert "{urn:ietf:params:xml:ns:caldav}calendar-home-set" in chs
def testGetDefaultCalendar(self):
self.skip_on_compatibility_flag("no_default_calendar")
assert len(self.principal.calendars()) != 0
def testSearchShouldYieldData(self):
"""
ref https://github.com/python-caldav/caldav/issues/201
"""
c = self._fixCalendar()
if not self.check_compatibility_flag("read_only"):
## populate the calendar with an event or two or three
c.save_event(ev1)
c.save_event(ev2)
c.save_event(ev3)
objects = c.search(event=True)
## This will break if served a read-only calendar without any events
assert objects
## This was observed to be broken for @dreimer1986
assert objects[0].data
def testGetCalendar(self):
# Create calendar
c = self._fixCalendar()
assert c.url is not None
assert len(self.principal.calendars()) != 0
str_ = str(c)
repr_ = repr(c)
## Not sure if those asserts make much sense, the main point here is to exercise
## the __str__ and __repr__ methods on the Calendar object.
if not self.check_compatibility_flag("no_displayname"):
name = c.get_property(dav.DisplayName(), use_cached=True)
if not name:
name = c.url
assert str(name) == str_
assert "Calendar" in repr(c)
assert str(c.url) in repr(c)
def testProxy(self):
if self.caldav.url.scheme == "https":
pytest.skip(
"Skipping %s.testProxy as the TinyHTTPProxy "
"implementation doesn't support https"
)
self.skip_on_compatibility_flag("no_default_calendar")
server_address = ("127.0.0.1", 8080)
try:
proxy_httpd = NonThreadingHTTPServer(
server_address, ProxyHandler, logging.getLogger("TinyHTTPProxy")
)
except:
pytest.skip("Unable to set up proxy server")
threadobj = threading.Thread(target=proxy_httpd.serve_forever)
conn_params = self.server_params.copy()
for special in ("setup", "teardown", "name"):
if special in conn_params:
conn_params.pop(special)
try:
threadobj.start()
assert threadobj.is_alive()
conn_params["proxy"] = proxy
c = client(**conn_params)
p = c.principal()
assert len(p.calendars()) != 0
finally:
proxy_httpd.shutdown()
# this should not be necessary, but I've observed some failures
if threadobj.is_alive():
time.sleep(0.15)
assert not threadobj.is_alive()
threadobj = threading.Thread(target=proxy_httpd.serve_forever)
try:
threadobj.start()
assert threadobj.is_alive()
conn_params["proxy"] = proxy_noport
c = client(**conn_params)
p = c.principal()
assert len(p.calendars()) != 0
assert threadobj.is_alive()
finally:
proxy_httpd.shutdown()
# this should not be necessary
if threadobj.is_alive():
time.sleep(0.05)
assert not threadobj.is_alive()
def _notFound(self):
if self.check_compatibility_flag("non_existing_raises_other"):
return error.DAVError
else:
return error.NotFoundError
def testPrincipal(self):
collections = self.principal.calendars()
if "principal_url" in self.server_params:
assert self.principal.url == self.server_params["principal_url"]
for c in collections:
assert c.__class__.__name__ == "Calendar"
def testCreateDeleteCalendar(self):
self.skip_on_compatibility_flag("no_mkcalendar")
self.skip_on_compatibility_flag("read_only")
self.skip_on_compatibility_flag("no_delete_calendar")
if not self.check_compatibility_flag(
"unique_calendar_ids"
) and self.cleanup_regime in ("light", "pre"):
self._teardownCalendar(cal_id=self.testcal_id)
c = self.principal.make_calendar(name="Yep", cal_id=self.testcal_id)
assert c.url is not None
events = c.events()
assert len(events) == 0
events = self.principal.calendar(name="Yep", cal_id=self.testcal_id).events()
assert len(events) == 0
c.delete()
# this breaks with zimbra and radicale
if not self.check_compatibility_flag("non_existing_calendar_found"):
with pytest.raises(self._notFound()):
self.principal.calendar(name="Yep", cal_id=self.testcal_id).events()
def testChangeAttendeeStatusWithEmailGiven(self):
self.skip_on_compatibility_flag("read_only")
c = self._fixCalendar()
event = c.save_event(
uid="test1",
dtstart=datetime(2015, 10, 10, 8, 7, 6),
dtend=datetime(2015, 10, 10, 9, 7, 6),
ical_fragment="ATTENDEE;ROLE=OPT-PARTICIPANT;PARTSTAT=TENTATIVE:MAILTO:testuser@example.com",
)
event.change_attendee_status(
attendee="testuser@example.com", PARTSTAT="ACCEPTED"
)
event.save()
self.skip_on_compatibility_flag("object_by_uid_is_broken")
event = c.event_by_uid("test1")
## TODO: work in progress ... see https://github.com/python-caldav/caldav/issues/399
def testCreateEvent(self):
self.skip_on_compatibility_flag("read_only")
c = self._fixCalendar()
existing_events = c.events()
if not self.check_compatibility_flag("no_mkcalendar"):
## we're supposed to be working towards a brand new calendar
assert len(existing_events) == 0
# add event
c.save_event(broken_ev1)
# c.events() should give a full list of events
events = c.events()
assert len(events) == len(existing_events) + 1
# We should be able to access the calender through the URL
c2 = self.caldav.calendar(url=c.url)
events2 = c2.events()
assert len(events2) == len(existing_events) + 1
assert events2[0].url == events[0].url
if not self.check_compatibility_flag(
"no_mkcalendar"
) and not self.check_compatibility_flag("no_displayname"):
# We should be able to access the calender through the name
c2 = self.principal.calendar(name="Yep")
## may break if we have multiple calendars with the same name
if not self.check_compatibility_flag("no_delete_calendar"):
assert c2.url == c.url
events2 = c2.events()
assert len(events2) == 1
assert events2[0].url == events[0].url
# add another event, it should be doable without having premade ICS
ev2 = c.save_event(
dtstart=datetime(2015, 10, 10, 8, 7, 6),
summary="This is a test event",
dtend=datetime(2016, 10, 10, 9, 8, 7),
uid="ctuid1",
)
events = c.events()
assert len(events) == len(existing_events) + 2
ev2.delete()
def testAlarm(self):
## Ref https://github.com/python-caldav/caldav/issues/132
c = self._fixCalendar()
ev = c.save_event(
dtstart=datetime(2015, 10, 10, 8, 0, 0),
summary="This is a test event",
dtend=datetime(2016, 10, 10, 9, 0, 0),
alarm_trigger=timedelta(minutes=-15),
alarm_action="AUDIO",
)
self.skip_on_compatibility_flag("no_alarmsearch")
## So we have an alarm that goes off 07:45 for an event starting 08:00