Skip to content

Commit c2f72c3

Browse files
committed
looking through the examples. I think I'll just let them stay - but they should be tested
1 parent 01e34d1 commit c2f72c3

4 files changed

Lines changed: 41 additions & 25 deletions

File tree

caldav/davclient.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -524,9 +524,9 @@ def __enter__(self) -> Self:
524524

525525
def __exit__(
526526
self,
527-
exc_type: Optional[BaseException],
528-
exc_value: Optional[BaseException],
529-
traceback: Optional[TracebackType],
527+
exc_type: Optional[BaseException] = None,
528+
exc_value: Optional[BaseException] = None,
529+
traceback: Optional[TracebackType] = None,
530530
) -> None:
531531
self.close()
532532
## Used for tests, to tear down a temporarily test server
@@ -966,7 +966,7 @@ def get_davclient(
966966
if environment:
967967
conf = {}
968968
for conf_key in (x for x in os.environ if x.startswith("CALDAV_")):
969-
conf[conf_key[7:]] = os.environ[conf_key].lower()
969+
conf[conf_key[7:].lower()] = os.environ[conf_key]
970970
if conf:
971971
return DAVClient(**conf)
972972
config_file = os.environ.get("CALDAV_CONFIG_FILE")

examples/get_events_example.py

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,48 @@
11
#!/usr/bin/env python3
22
import json
3-
from os import environ as env
43

5-
import caldav
4+
## Code contributed by Крылов Александр. Minor changes and quite some
5+
## comments by Tobias Brox.
66

7-
username = env["CALDAV_USERNAME"]
8-
password = env["CALDAV_PASSWORD"]
9-
url = env["CALDAV_URL"]
10-
caldav_url = f"https://{url}/{username}/"
11-
headers = {}
7+
## Set CALDAV_USERNAME, CALDAV_URL and CALDAV_PASSWORD through
8+
## environment variables before running this example
129

10+
from caldav.davclient import get_davclient
1311

1412
def fetch_and_print():
15-
with caldav.DAVClient(
16-
url=caldav_url,
17-
username=username,
18-
password=password,
19-
# Optional parameter to set HTTP headers on each request if needed
20-
headers=headers,
21-
) as client:
13+
with get_davclient() as client:
2214
print_calendars_demo(client.principal().calendars())
2315

24-
2516
def print_calendars_demo(calendars):
2617
if not calendars:
2718
return
2819
events = []
2920
for calendar in calendars:
3021
for event in calendar.events():
22+
## Most calendar events will have only one component,
23+
## and it can be accessed simply as event.component
24+
## The exception is special recurrences, to handle those
25+
## we may need to do the walk:
3126
for component in event.icalendar_instance.walk():
3227
if component.name != "VEVENT":
3328
continue
3429
events.append(fill_event(component, calendar))
3530
print(json.dumps(events, indent=2, ensure_ascii=False))
3631

37-
3832
def fill_event(component, calendar) -> dict[str, str]:
33+
## quite some data is tossed away here - like, the recurring rule.
3934
cur = {}
4035
cur["calendar"] = f"{calendar}"
4136
cur["summary"] = component.get("summary")
4237
cur["description"] = component.get("description")
43-
cur["start"] = component.get("dtstart").dt.strftime("%m/%d/%Y %H:%M")
44-
endDate = component.get("dtend")
45-
if endDate and endDate.dt:
46-
cur["end"] = endDate.dt.strftime("%m/%d/%Y %H:%M")
38+
cur["start"] = component.start.strftime("%m/%d/%Y %H:%M")
39+
endDate = component.end
40+
if endDate:
41+
cur["end"] = endDate.strftime("%m/%d/%Y %H:%M")
42+
## For me the following line breaks because some imported calendar events
43+
## came without dtstamp. But dtstamp is mandatory according to the RFC
4744
cur["datestamp"] = component.get("dtstamp").dt.strftime("%m/%d/%Y %H:%M")
4845
return cur
4946

50-
5147
if __name__ == "__main__":
5248
fetch_and_print()

tests/test_caldav.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,7 @@ def testEnvironment(self):
456456
os.environ["PYTHON_CALDAV_USE_TEST_SERVER"] = "1"
457457
with get_davclient(environment=True, config_file=False, name="-1") as conn:
458458
assert conn.principal()
459+
del os.environ["PYTHON_CALDAV_USE_TEST_SERVER"]
459460
for key in ("url", "username", "password", "proxy"):
460461
if key in caldav_servers[-1]:
461462
os.environ[f"CALDAV_{key.upper()}"] = caldav_servers[-1][key]

tests/test_examples.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import os
2+
import sys
3+
from caldav.davclient import get_davclient
4+
from datetime import datetime
5+
6+
class TestExamples:
7+
def setup_method(self):
8+
os.environ['PYTHON_CALDAV_USE_TEST_SERVER'] = '1'
9+
sys.path.insert(0,'.')
10+
sys.path.insert(1,'..')
11+
def teardown_method(self):
12+
sys.path = sys.path[2:]
13+
del os.environ['PYTHON_CALDAV_USE_TEST_SERVER']
14+
def test_get_events_example(self):
15+
with get_davclient() as client:
16+
mycal = client.principal().make_calendar(name="Test calendar")
17+
mycal.save_event(dtstart=datetime(2025,5,3,10), dtend=datetime(2025,5,3,11),summary="testevent")
18+
from examples import get_events_example
19+
get_events_example.fetch_and_print()

0 commit comments

Comments
 (0)