174 lines
7.7 KiB
Python
174 lines
7.7 KiB
Python
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'<img src="{attachment["url"]}">'
|
|
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"], '<img src="u2/a1">') # 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): # Storage answers 400, the real reason in the body
|
|
self.sb.fail["/storage/v1/object/attachments/"] = (400, {"statusCode": "413", "code": "EntityTooLarge"})
|
|
self.assertEqual(self.run_once(), 2)
|
|
self.assertTrue(any("skipped: 400 EntityTooLarge" in l for l in self.lines))
|
|
self.assertIn("conversations", self.sb.tables["checkpoints"])
|
|
|
|
def test_missing_bucket_stops_the_run(self): # not an attachment's fault: never skip and lose them all
|
|
self.sb.fail["/storage/v1/object/attachments/"] = (400, {"statusCode": "404", "code": "NoSuchBucket"})
|
|
with self.assertRaises(urllib.error.HTTPError) as cm:
|
|
self.run_once()
|
|
cm.exception.close()
|
|
self.assertNotIn("conversations", self.sb.tables["checkpoints"])
|
|
|
|
def test_non_http_attachment_skipped(self): # Lecteur refuses it (ValueError): skipped, never blocks the runs
|
|
self.serve(piece("passwd", "file:///etc/passwd", uuid="a1"))
|
|
self.assertEqual(self.run_once(), 2)
|
|
self.assertTrue(self.sb.tables["messages"]["m08:00"]["raw"]["attachments"][0]["absent"])
|
|
self.assertIn("conversations", self.sb.tables["checkpoints"])
|
|
|
|
def test_failure_names_the_conversation(self):
|
|
self.sb.fail["/rest/v1/messages"] = 500
|
|
with self.assertRaises(urllib.error.HTTPError) as cm:
|
|
self.run_once()
|
|
cm.exception.close()
|
|
self.assertTrue(any("#2" in l and "u2" in l for l in self.lines))
|
|
|
|
def test_same_message_twice_saved_once(self): # a page shift while a long thread is read repeats a message
|
|
m = message("09:00")
|
|
self.ld.reponses[("GET", "/api/v1/conversations/u1/messages")] = pages([m, dict(m)])
|
|
self.assertEqual(self.run_once(), 2)
|
|
self.assertEqual(self.sb.tables["messages"]["m09:00"]["conversation_uuid"], "u1")
|
|
|
|
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()
|