Refactor to unified caesar() function with encode/decode support

- Replace separate encrypt/decrypt with shared caesar() function
- Add direction constants (DIRECTION_ENCODE, DIRECTION_DECODE) and
  prompts
- Update main.py to support interactive encode/decode loop
- Keep encrypt/decrypt as wrappers for backward compatibility
- Add tests for caesar() with both directions and error handling
- Update tests for main.py with interactive scenario tests
This commit is contained in:
2026-10-04 13:23:47 +08:00
parent d4b3e6ab19
commit 9d8beb3aef
8 changed files with 139 additions and 33 deletions
+23 -8
View File
@@ -1,14 +1,21 @@
## @file cipher.py
# @brief Caesar cipher encryption and decryption.
# @brief Caesar cipher: one shared function for encoding and decoding.
from caesar_cipher.constants import ALPHABET
from caesar_cipher.constants import ALPHABET, DIRECTION_DECODE, DIRECTION_ENCODE
def encrypt(text: str, shift: int) -> str:
## @brief Encrypt a text with the Caesar cipher.
# @param text Original text.
# @param shift Positions to move each letter (may be negative or > 26).
# @return The encrypted text; non-letters are kept, case is preserved.
def caesar(text: str, shift: int, direction: str) -> str:
## @brief Encode or decode a text with the Caesar cipher.
# @param text Text to transform.
# @param shift Positions to move each letter (may be negative or > 26).
# @param direction DIRECTION_ENCODE or DIRECTION_DECODE.
# @return The transformed text; non-letters are kept, case is preserved.
# @throws ValueError If direction is not a known direction.
if direction == DIRECTION_DECODE:
shift = -shift
elif direction != DIRECTION_ENCODE:
raise ValueError(f"Unknown direction: {direction!r}")
result = []
for char in text:
lower = char.lower()
@@ -21,9 +28,17 @@ def encrypt(text: str, shift: int) -> str:
return "".join(result)
def encrypt(text: str, shift: int) -> str:
## @brief Encrypt a text with the Caesar cipher.
# @param text Original text.
# @param shift Number of positions to shift forward.
# @return The encrypted text.
return caesar(text, shift, DIRECTION_ENCODE)
def decrypt(text: str, shift: int) -> str:
## @brief Decrypt a Caesar-cipher text.
# @param text Encrypted text.
# @param shift Shift that was used to encrypt.
# @return The original text.
return encrypt(text, -shift)
return caesar(text, shift, DIRECTION_DECODE)