In Python cryptography, writing unit tests is essential for ensuring the reliability and correctness of your cryptographic operations. Unit tests help verify that your cryptographic functions behave as expected, especially when it comes to encryption, decryption, and key management. Below is an example of how to write unit tests for a simple encryption and decryption function using the `cryptography` library.
import unittest
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
def encrypt_message(message, key):
fernet = Fernet(key)
return fernet.encrypt(message.encode())
def decrypt_message(encrypted_message, key):
fernet = Fernet(key)
return fernet.decrypt(encrypted_message).decode()
class TestCryptography(unittest.TestCase):
def setUp(self):
self.key = generate_key()
def test_encryption_decryption(self):
original_message = "Hello, World!"
encrypted_message = encrypt_message(original_message, self.key)
decrypted_message = decrypt_message(encrypted_message, self.key)
self.assertEqual(original_message, decrypted_message)
def test_different_keys(self):
different_key = generate_key()
original_message = "Test message"
encrypted_message = encrypt_message(original_message, self.key)
with self.assertRaises(Exception):
decrypt_message(encrypted_message, different_key)
if __name__ == "__main__":
unittest.main()
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?