import io
import unittest
import urllib.error
from conversations.pomper import Lecteur
from fake_supabase import FakeSupabase
from faux_libredesk import FauxLibreDesk
from poller.poll import Supabase, loop, poll_once
from test_pomper import conv, message, pages, piece
LIST = ("GET", "/api/v1/conversations/all")
def stop(_):
raise StopIteration
class TestPoll(unittest.TestCase):
def setUp(self):
self.ld, self.s3, self.sb = FauxLibreDesk(), FauxLibreDesk(), FakeSupabase()
for f in (self.ld.arreter, self.s3.arreter, self.sb.stop):
self.addCleanup(f)
self.lines = []
self.s3.reponses[("GET", "/x.png")] = b"PNG"
self.serve(piece("photo.png", f"{self.s3.url}/x.png?X-Amz-Signature=secret", uuid="a1"))
def serve(self, attachment):
convs = [conv("2", "u2", "2026-11-18T12:00:00Z"), conv("1", "u1", "2026-11-16T12:00:00Z")]
img = f'
'
msgs = {"u2": [message("08:00", [attachment], contenu=img)], "u1": [message("09:00")]}
self.ld.reponses[LIST] = pages(convs)
for c in convs:
self.ld.reponses[("GET", f"/api/v1/conversations/{c['uuid']}/messages")] = pages(msgs[c["uuid"]])
def run_once(self, key="sb_secret_x"):
return poll_once(Lecteur(self.ld.url, "k", "s"), Supabase(self.sb.url, key), log=self.lines.append)
def libredesk_paths(self):
return [p.split("?")[0] for _, p, _ in self.ld.requetes]
def test_first_run_everything(self):
self.assertEqual(self.run_once(), 2)
convs = self.sb.tables["conversations"]
self.assertEqual(set(convs), {"u2", "u1"})
self.assertNotIn("previous_conversations", convs["u2"]["raw"])
self.assertEqual(convs["u2"]["contact_email"], "j@x.ch")
self.assertEqual(convs["u2"]["reference_number"], "2")
self.assertEqual(self.sb.objects["u2/a1"], b"PNG")
m = self.sb.tables["messages"]["m08:00"]
self.assertEqual(m["conversation_uuid"], "u2")
self.assertEqual(m["raw"]["attachments"][0]["url"], "u2/a1")
self.assertEqual(m["raw"]["content"], '
') # the signed URL expires: replaced by the key
self.assertIn("conversations", self.sb.tables["checkpoints"])
def test_second_run_no_duplicates(self):
self.run_once()
self.sb.tables["checkpoints"].clear() # no checkpoint: everything is read again
self.run_once()
self.assertEqual(len(self.sb.tables["conversations"]), 2)
self.assertEqual(len(self.sb.tables["messages"]), 2)
self.assertEqual(len(self.s3.requetes), 1) # the attachment downloaded once
def test_incremental(self):
self.sb.tables["checkpoints"]["conversations"] = {"name": "conversations", "until": "2026-11-18T10:00:00+00:00"}
self.assertEqual(self.run_once(), 1)
self.assertEqual(set(self.sb.tables["conversations"]), {"u2"})
self.assertNotIn("/api/v1/conversations/u1/messages", self.libredesk_paths())
self.assertNotEqual(self.sb.tables["checkpoints"]["conversations"]["until"], "2026-11-18T10:00:00+00:00")
def test_failure_checkpoint_unchanged(self):
self.sb.fail["/rest/v1/messages"] = 500
with self.assertRaises(urllib.error.HTTPError) as cm:
self.run_once()
cm.exception.close()
self.assertNotIn("conversations", self.sb.tables["checkpoints"])
def test_lost_attachment_skipped(self):
self.s3.reponses[("GET", "/x.png")] = 404
self.assertEqual(self.run_once(), 2)
self.assertTrue(self.sb.tables["messages"]["m08:00"]["raw"]["attachments"][0]["absent"])
self.assertTrue(any("skipped: 404" in l for l in self.lines))
self.assertIn("conversations", self.sb.tables["checkpoints"])
def test_attachment_refused_by_storage_skipped(self):
self.sb.fail["/storage/v1/object/attachments/"] = 413
self.assertEqual(self.run_once(), 2)
self.assertTrue(any("skipped: 413" in l for l in self.lines))
self.assertIn("conversations", self.sb.tables["checkpoints"])
def test_other_storage_error_stops_the_run(self): # a passing failure: the next run starts again
self.sb.fail["/storage/v1/object/attachments/"] = 500
with self.assertRaises(urllib.error.HTTPError) as cm:
self.run_once()
cm.exception.close()
self.assertNotIn("conversations", self.sb.tables["checkpoints"])
def test_attachment_without_uuid(self):
self.serve(piece("photo.png", f"{self.s3.url}/x.png", uuid=None))
self.run_once()
self.assertIn("u2/m08:00-0", self.sb.objects)
def test_keys_each_to_its_own(self):
self.run_once()
for _, _, h in self.sb.requests:
self.assertEqual(h.get("apikey"), "sb_secret_x")
self.assertNotIn("authorization", h)
self.assertTrue(all("sb_secret_x" not in str(h) for h in self.ld.entetes + self.s3.entetes))
self.assertTrue(all("token k:s" not in str(h) for h in self.s3.entetes))
def test_jwt_also_in_authorization(self):
self.run_once(key="eyJabc")
self.assertEqual(self.sb.requests[0][2]["authorization"], "Bearer eyJabc")
def test_no_write_to_libredesk(self):
self.run_once()
self.assertEqual(self.ld.ecritures(), [])
def test_loop_continues_after_error(self):
calls = []
def run():
calls.append(1)
if len(calls) == 1:
raise urllib.error.URLError("down")
return 0
def sleep(_):
if len(calls) >= 2:
raise StopIteration
with self.assertRaises(StopIteration):
loop(run, 300, self.lines.append, sleep)
self.assertEqual(len(calls), 2)
self.assertTrue(any("down" in l for l in self.lines))
def test_log_without_signature(self):
def run():
raise urllib.error.HTTPError("https://s3/x.png?X-Amz-Signature=secret", 500, "", {}, io.BytesIO())
with self.assertRaises(StopIteration):
loop(run, 300, self.lines.append, stop)
self.assertTrue(any("https://s3/x.png" in l for l in self.lines))
self.assertFalse(any("secret" in l for l in self.lines))
if __name__ == "__main__":
unittest.main()