import unittest
from snapshot import checked_snapshot, fingerprint, prepare


class SnapshotTests(unittest.TestCase):
    def setUp(self):
        self.snapshot = prepare(["test@example.invalid"], "Draft", "Review this", [("report.txt", b"first")])
        self.approved = fingerprint(self.snapshot)

    def test_unchanged_returns_the_exact_snapshot(self):
        self.assertIs(checked_snapshot(self.snapshot, self.approved), self.snapshot)

    def test_same_filename_replaced_content_requires_review(self):
        other = prepare(self.snapshot.recipients, "Draft", "Review this", [("report.txt", b"other")])
        with self.assertRaises(PermissionError):
            checked_snapshot(other, self.approved)

    def test_recipient_subject_and_body_are_bound(self):
        for recipients, subject, body in [(["other@example.invalid"], "Draft", "Review this"),
                                          (self.snapshot.recipients, "Changed", "Review this"),
                                          (self.snapshot.recipients, "Draft", "Changed")]:
            with self.assertRaises(PermissionError):
                checked_snapshot(prepare(recipients, subject, body, [("report.txt", b"first")]), self.approved)

    def test_original_buffer_changes_do_not_change_approved_bytes(self):
        buffer = bytearray(b"first")
        snapshot = prepare(["test@example.invalid"], "Draft", "Review this", [("report.txt", buffer)])
        approved = fingerprint(snapshot)
        buffer[:] = b"other"
        self.assertEqual(checked_snapshot(snapshot, approved).attachments[0].content, b"first")


if __name__ == "__main__":
    unittest.main()
