Files
ldap2nextcloud/tests/test_sync.py
T
zeguiguiandClaude Opus 5.5 f6a01b85e1 🤖 ldap2nextcloud : synchronisation LDAP vers un carnet Nextcloud (CardDAV)
Historique regroupé en un seul commit pour ne pas publier de données
de production.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:47:31 +01:00

260 lines
8.6 KiB
Python

import logging
from io import BytesIO
from pathlib import Path
import pytest
from PIL import Image
from ldap2nextcloud.carddav import CardDavError
from ldap2nextcloud.config import Settings, load_directions, load_mapping
from ldap2nextcloud.model import contact_href
from ldap2nextcloud.planner import GuardError
from ldap2nextcloud.state import StateDB
from ldap2nextcloud.sync import run_sync
ROOT = Path(__file__).resolve().parent.parent
MAPPING = load_mapping(ROOT / "mapping.example.yaml")
DIRECTIONS = load_directions(ROOT / "directions.example.yaml")
def make_settings(tmp_path):
return Settings(
ldap_url="ldap://mock", ldap_bind_dn=None, ldap_bind_password=None,
ldap_base_dn="dc=x", ldap_filter="(objectClass=*)", ldap_birthday_filter="(x=1)",
ldap_group_dns=[], ldap_ca_cert=None, nextcloud_url="https://cloud.test",
nextcloud_user="u", nextcloud_app_password="p", nextcloud_addressbook="b",
state_db=tmp_path / "state" / "sync.sqlite", mapping_file=Path("m"),
directions_file=Path("d"),
)
def photo():
buffer = BytesIO()
Image.new("RGB", (800, 800), (10, 20, 30)).save(buffer, format="JPEG")
return buffer.getvalue()
PEOPLE = [
("omalmare", "Oscar", "MALMARE", "9052", "620", "19680615000000Z"),
("cbarssac", "Cédric", "BARSSAC", "4136", "620", "19660825000000Z"),
("lvernet", "Lucie", "VERNET", "7781", "210", "19790102000000Z"),
]
def raw(uid, given, sn, phone, direction, birth):
return {
"uid": [uid.encode()], "givenName": [given.encode()], "sn": [sn.encode()],
"cn": [f"{sn} {given}".encode()], "mail": [f"{uid}@example.org".encode()],
"telephoneNumber": [phone.encode()], "usrDirectionId": [direction.encode()],
"usrDateNaissance": [birth.encode()], "jpegPhoto": [photo()],
}
class FakeSource:
def __init__(self, people=PEOPLE):
self.entries = [raw(*p) for p in people]
def fetch_entries(self, attributes):
return self.entries
def fetch_birthday_keys(self, key_attr):
return {"omalmare"}
class FakeClient:
def __init__(self, cards=None, return_etag=True):
self.cards = dict(cards or {}) # href -> (etag, text)
self.counter = 0
self.puts = []
self.deletes = []
self.fail = set()
self.return_etag = return_etag
def list_etags(self):
return {href: etag for href, (etag, _) in self.cards.items()}
def multiget(self, hrefs):
return {h: self.cards[h][1] for h in hrefs if h in self.cards}
def put(self, href, vcard, etag):
if href in self.fail:
raise CardDavError("refus", 412)
if etag is not None and self.cards.get(href, (None,))[0] != etag:
raise CardDavError("etag", 412)
self.counter += 1
new = f"e{self.counter}"
self.cards[href] = (new, vcard)
self.puts.append((href, etag))
return new if self.return_etag else None
def delete(self, href, etag):
self.cards.pop(href, None)
self.deletes.append(href)
def run(tmp_path, client, source=None, **kwargs):
settings = make_settings(tmp_path)
with StateDB(settings.state_db) as state:
return run_sync(settings, MAPPING, DIRECTIONS, source or FakeSource(), client, state, **kwargs)
def test_first_run_creates_all_and_purges_legacy(tmp_path):
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
summary = run(tmp_path, client, initial=True)
assert (summary.created, summary.deleted, summary.errors) == (3, 1, 0)
with StateDB(make_settings(tmp_path).state_db) as state:
rows = state.all()
assert len(rows) == 3 and all(r.etag for r in rows.values())
assert "ldap2vcard-old.vcf" not in client.cards
def test_birthday_only_for_selected_keys(tmp_path):
client = FakeClient()
run(tmp_path, client)
assert "BDAY:1968-06-15" in client.cards[contact_href("omalmare")][1]
assert "BDAY" not in client.cards[contact_href("lvernet")][1]
def test_photo_is_resized(tmp_path):
client = FakeClient()
run(tmp_path, client)
import vobject
card = vobject.readOne(client.cards[contact_href("omalmare")][1])
assert Image.open(BytesIO(card.photo.value)).size == (512, 512)
def test_second_run_without_change_does_nothing(tmp_path):
client = FakeClient()
run(tmp_path, client)
client.puts.clear()
summary = run(tmp_path, client)
assert summary.unchanged == 3 and not client.puts and not client.deletes
def test_changed_entry_is_updated_only(tmp_path):
client = FakeClient()
run(tmp_path, client)
client.puts.clear()
source = FakeSource()
source.entries[2]["usrDirectionId"] = [b"620"]
summary = run(tmp_path, client, source)
assert summary.updated == 1 and summary.unchanged == 2
href, etag = client.puts[0]
assert href == contact_href("lvernet") and etag is not None
def test_lost_state_rebuilds_without_put(tmp_path):
client = FakeClient()
run(tmp_path, client)
make_settings(tmp_path).state_db.unlink()
client.puts.clear()
summary = run(tmp_path, client)
assert summary.verified == 3 and not client.puts
with StateDB(make_settings(tmp_path).state_db) as state:
assert len(state.all()) == 3
def test_lost_state_with_stale_card_is_updated(tmp_path):
href = contact_href("omalmare")
client = FakeClient({href: ("e0", "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:x\r\nN:x;;;;\r\nEND:VCARD\r\n")})
summary = run(tmp_path, client)
assert summary.updated == 1 and summary.created == 2
assert (href, "e0") in client.puts
def test_dry_run_writes_nothing(tmp_path):
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
summary = run(tmp_path, client, dry_run=True, initial=True)
assert summary.created == 3 and summary.deleted == 1
assert not client.puts and not client.deletes
with StateDB(make_settings(tmp_path).state_db) as state:
assert state.all() == {}
def test_put_error_is_counted_and_not_stored(tmp_path):
client = FakeClient()
client.fail.add(contact_href("cbarssac"))
summary = run(tmp_path, client)
assert summary.errors == 1 and summary.created == 2
with StateDB(make_settings(tmp_path).state_db) as state:
assert contact_href("cbarssac") not in state.all()
def test_guard_error_before_any_write(tmp_path):
client = FakeClient({f"old{i}.vcf": ("x", "") for i in range(1270)})
with pytest.raises(GuardError):
run(tmp_path, client)
assert not client.puts and not client.deletes
def test_empty_ldap_aborts(tmp_path):
client = FakeClient()
with pytest.raises(GuardError):
run(tmp_path, client, FakeSource(people=[]), force=True)
def test_missing_etag_in_put_response_is_refreshed(tmp_path):
client = FakeClient(return_etag=False)
run(tmp_path, client)
with StateDB(make_settings(tmp_path).state_db) as state:
rows = state.all()
assert all(rows[h].etag == client.cards[h][0] for h in rows)
def test_logs_contain_no_personal_data(tmp_path, caplog):
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
client.fail.add(contact_href("cbarssac"))
with caplog.at_level(logging.DEBUG):
run(tmp_path, client, initial=True)
for _, given, sn, phone, _, birth in PEOPLE:
for secret in (given, sn, phone, birth[:8], "example.org"):
assert secret not in caplog.text
def test_unexpected_photo_failure_does_not_stop_the_run(tmp_path, monkeypatch):
from ldap2nextcloud import sync
calls = {"n": 0}
def flaky(data, size, quality):
calls["n"] += 1
if calls["n"] == 1:
raise RuntimeError("bombe")
return b"\xff\xd8ok"
monkeypatch.setattr(sync, "resize_photo", flaky)
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
summary = run(tmp_path, client, initial=True)
assert summary.errors == 1 and summary.created == 2 and summary.deleted == 1
class RecordingProgress:
def __init__(self):
self.total = None
self.advanced = 0
self.closed = False
def start(self, total):
self.total = total
def advance(self):
self.advanced += 1
def close(self):
self.closed = True
def test_progress_covers_every_write_including_errors(tmp_path):
client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")})
client.fail.add(contact_href("cbarssac"))
progress = RecordingProgress()
run(tmp_path, client, initial=True, progress=progress)
assert progress.total == 4 and progress.advanced == 4 and progress.closed
def test_dry_run_does_not_start_progress(tmp_path):
progress = RecordingProgress()
run(tmp_path, FakeClient(), dry_run=True, progress=progress)
assert progress.total is None