import importlib.util import tempfile import unittest from pathlib import Path SPEC = importlib.util.spec_from_file_location("members_server", Path(__file__).resolve().parents[1] / "services" / "members" / "server.py") server = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(server) UID = "6812345678901234" class ClaimTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.now = 1_790_000_000 self.bio = "" self.found = UID self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now, fetcher=self.fetch) def fetch(self, unique_id): return (self.found, self.bio) def test_code_is_stable_and_per_account(self): code = self.registry.code(UID) self.assertEqual(code, self.registry.code(UID)) self.assertNotEqual(code, self.registry.code("6812345678901235")) self.assertRegex(code, r"^LT-[A-Z2-7]{8}$") def test_bio_with_the_code_gets_the_badge(self): self.assertFalse(self.registry.lookup([UID])["niche"][UID]) self.assertEqual("code_missing", self.registry.claim(UID, "someone")["reason"]) self.bio = "hello " + self.registry.code(UID) + " bye" self.assertTrue(self.registry.claim(UID, "someone")["granted"]) self.assertTrue(self.registry.lookup([UID])["niche"][UID]) def test_someone_elses_profile_is_refused(self): self.found = "999999999" self.bio = self.registry.code(UID) with self.assertRaises(ValueError): self.registry.claim(UID, "someone") def test_nothing_is_issued_after_the_deadline_but_holders_stay(self): self.bio = self.registry.code(UID) self.registry.claim(UID, "someone") self.now = server.CLAIM_DEADLINE + 1 other = "6812345678901299" self.found, self.bio = other, self.registry.code(other) with self.assertRaises(ValueError): self.registry.claim(other, "other") self.assertTrue(self.registry.lookup([UID, other])["niche"][UID]) self.assertFalse(self.registry.lookup([UID, other])["niche"][other]) def test_blocked_accounts_get_nothing(self): with self.registry.connect() as db: db.execute("INSERT INTO blocked(uid) VALUES(?)", (UID,)) self.bio = self.registry.code(UID) with self.assertRaises(ValueError): self.registry.claim(UID, "someone") def test_bad_input_and_unreadable_profiles(self): with self.assertRaises(ValueError): self.registry.claim("abc", "someone") with self.assertRaises(ValueError): self.registry.claim(UID, "bad name!") self.registry.fetcher = lambda u: (_ for _ in ()).throw(OSError("blocked")) with self.assertRaises(ValueError): self.registry.claim(UID, "someone") if __name__ == "__main__": unittest.main()