diff --git a/pyedgeon/__init__.py b/pyedgeon/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14f92a343ba447f17b7209a22e563d9e5e9dc0af --- /dev/null +++ b/pyedgeon/__init__.py @@ -0,0 +1 @@ +from .pyedgeon import * diff --git a/pyedgeon/pyedgeon.py b/pyedgeon/pyedgeon.py new file mode 100644 index 0000000000000000000000000000000000000000..0e1a1d6638a4c5a95e0a1e71a350dc331087bde9 --- /dev/null +++ b/pyedgeon/pyedgeon.py @@ -0,0 +1,679 @@ +from PIL import ImageFont +from PIL import Image +from PIL import ImageDraw +from PIL import ImageOps +from math import sqrt +from string import digits +from pathlib import Path +import logging +import os +import numpy as np + +# Set up logging +logger = logging.getLogger(__name__) + + +class PyedgeonError(Exception): + """Base exception for Pyedgeon errors""" + pass + + +class ValidationError(PyedgeonError): + """Input validation error""" + pass + + +class FileOperationError(PyedgeonError): + """File operation error""" + pass + + +class Pyedgeon(): + + """ + Creates a pyedgeon object + """ + + # Common system font paths (searched in order) + SYSTEM_FONT_PATHS = [ + # macOS + "/System/Library/Fonts/Helvetica.ttc", + "/System/Library/Fonts/HelveticaNeue.ttc", + "/Library/Fonts/Arial.ttf", + # Linux - DejaVu (most common) + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans-ExtraLight.ttf", + # Linux - Liberation + "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", + "/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf", + # Linux - Ubuntu + "/usr/share/fonts/truetype/ubuntu/Ubuntu-L.ttf", + # Windows + "C:/Windows/Fonts/Arial.ttf", + "C:/Windows/Fonts/arial.ttf", + "C:/Windows/Fonts/calibri.ttf", + ] + + @classmethod + def find_system_font(cls): + """ + Find first available system font. + + Returns: + str: Path to system font + + Raises: + FileNotFoundError: If no system font is found + """ + for font_path in cls.SYSTEM_FONT_PATHS: + if Path(font_path).exists(): + logger.info(f"Auto-detected system font: {font_path}") + return font_path + + # If no font found, provide helpful error message + raise FileNotFoundError( + "No system font found. Please specify font_path parameter.\n\n" + "Common font locations:\n" + " macOS: /System/Library/Fonts/Helvetica.ttc\n" + " Linux: /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\n" + " Windows: C:/Windows/Fonts/Arial.ttf\n\n" + "Example:\n" + " img = Pyedgeon(\n" + " illusion_text='HELLO',\n" + " font_path='/path/to/your/font.ttf'\n" + " )" + ) + + def __init__(self, + illusion_text = "HELLO WORLD", + font_path = None, + num_rotations = 6, + file_ext = ".png", + text_color = (0, 0, 0), + background_color = (255, 255, 255), + img_side = 1024, + charmax = 22, + crop_width_x = 14, + crop_width_y = 5, + darkness_threshold = 116, + file_name = None, + file_path = "", + upper_case = True + ): + + """ + Default user-editable settings + + Args: + font_path: Path to TrueType font file. If None, will auto-detect system font. + """ + + if upper_case: + self.illusion_text = illusion_text.upper() + else: + self.illusion_text = illusion_text + + # Auto-detect font if not specified + if font_path is None: + self.font_path = self.find_system_font() + else: + self.font_path = font_path + self.num_rotations = num_rotations + self.file_ext = file_ext + self.text_color = text_color + self.background_color = background_color + self.img_side = img_side + self.charmax = charmax + self.file_path = file_path + self.font_size_guess = None + self.crop_width_x = crop_width_x + self.crop_width_y = crop_width_y + self.darkness_threshold = darkness_threshold + self.img_size = (self.img_side, self.img_side) + self.img_size_text = (self.img_side, self.img_side) + if file_name is not None: + self.file_name = file_name + else: + self.file_name = illusion_text + self.font_size = None + + # Apply validation + self._validate_inputs() + + def _validate_inputs(self): + """Validate all input parameters""" + self.text_color = self._validate_color(self.text_color, "text_color") + self.background_color = self._validate_color(self.background_color, "background_color") + self.num_rotations = self._validate_int(self.num_rotations, "num_rotations", min_val=1, max_val=360) + self.img_side = self._validate_int(self.img_side, "img_side", min_val=64, max_val=8192) + self.charmax = self._validate_int(self.charmax, "charmax", min_val=1, max_val=1000) + self.crop_width_x = self._validate_int(self.crop_width_x, "crop_width_x", min_val=0, max_val=500) + self.crop_width_y = self._validate_int(self.crop_width_y, "crop_width_y", min_val=0, max_val=500) + self.darkness_threshold = self._validate_int(self.darkness_threshold, "darkness_threshold", min_val=0, max_val=255) + self.illusion_text = self._validate_text(self.illusion_text) + self.font_path = self._validate_font_path(self.font_path) + self.file_ext = self._validate_extension(self.file_ext) + + def _validate_color(self, color, param_name): + """Validate RGB color tuple""" + if not isinstance(color, (tuple, list)): + raise ValidationError( + f"{param_name} must be a tuple or list, got {type(color).__name__}" + ) + + if len(color) != 3: + raise ValidationError( + f"{param_name} must have exactly 3 elements (R, G, B), got {len(color)}" + ) + + validated = [] + for i, component in enumerate(color): + if not isinstance(component, (int, float)): + raise ValidationError( + f"{param_name}[{i}] must be numeric, got {type(component).__name__}" + ) + + component = int(component) + if component < 0 or component > 255: + raise ValidationError( + f"{param_name}[{i}] must be in range 0-255, got {component}" + ) + + validated.append(component) + + return tuple(validated) + + def _validate_int(self, value, param_name, min_val=None, max_val=None): + """Validate integer parameter with bounds""" + if not isinstance(value, (int, float)): + raise ValidationError( + f"{param_name} must be numeric, got {type(value).__name__}" + ) + + try: + value = int(value) + except (ValueError, OverflowError) as e: + raise ValidationError( + f"{param_name} cannot be converted to integer: {e}" + ) + + if min_val is not None and value < min_val: + raise ValidationError( + f"{param_name} must be >= {min_val}, got {value}" + ) + if max_val is not None and value > max_val: + raise ValidationError( + f"{param_name} must be <= {max_val}, got {value}" + ) + + return value + + def _validate_text(self, text): + """Validate illusion text input""" + if not isinstance(text, str): + raise ValidationError(f"illusion_text must be a string, got {type(text).__name__}") + + max_absolute_length = 10000 + if len(text) > max_absolute_length: + raise ValidationError( + f"Text length ({len(text)}) exceeds absolute maximum ({max_absolute_length})" + ) + + if not text or not text.strip(): + raise ValidationError("illusion_text cannot be empty or whitespace only") + + if '\x00' in text: + raise ValidationError("illusion_text cannot contain null bytes") + + # Sanitize dangerous Unicode + dangerous_unicode = ['\u202e', '\u202d', '\u200e', '\u200f', '\ufeff'] + sanitized = text + for char in dangerous_unicode: + sanitized = sanitized.replace(char, '') + + return sanitized + + def _validate_font_path(self, font_path): + """Validate font file path for security""" + if not font_path: + raise ValidationError("Font path cannot be empty") + + # Validate file extension first (security check) + font_file = Path(font_path) + allowed_extensions = ['.ttf', '.otf', '.ttc', '.dfont'] + if font_file.suffix.lower() not in allowed_extensions: + raise ValidationError( + f"Invalid font extension: {font_file.suffix}. " + f"Allowed: {allowed_extensions}" + ) + + # If it's not an absolute path, check if it exists in current directory + if not font_file.is_absolute(): + # Check current directory + if not font_file.exists(): + # Try to find in system font directories + system_paths = [ + Path("/usr/share/fonts/truetype/dejavu"), + Path("/System/Library/Fonts"), + Path("C:/Windows/Fonts"), + ] + found = False + for sys_path in system_paths: + if sys_path.exists(): + candidate = sys_path / font_path + if candidate.exists(): + font_file = candidate + found = True + break + + if not found: + logger.warning( + f"Font file not found: {font_path}. " + f"Searched current directory and system font paths." + ) + # Return original path - will fail later with clear error + return font_path + else: + # Absolute path - validate it's safe + font_file = font_file.resolve() + + # If file exists, perform additional security checks + if font_file.exists(): + # Check if it's actually a file (not directory) + if not font_file.is_file(): + raise ValidationError(f"Font path is not a file: {font_path}") + + # Check file size (prevent DoS from huge fonts) + max_font_size = 10 * 1024 * 1024 # 10 MB + if font_file.stat().st_size > max_font_size: + raise ValidationError( + f"Font file too large: {font_file.stat().st_size} bytes (max: {max_font_size})" + ) + + return str(font_file) + + return font_path + + def _validate_extension(self, ext): + """Validate file extension""" + if not ext: + raise ValidationError("File extension cannot be empty") + + # Whitelist allowed extensions + allowed_extensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff'] + ext_lower = ext.lower() + + if ext_lower not in allowed_extensions: + raise ValidationError( + f"File extension '{ext}' not allowed. Allowed: {allowed_extensions}" + ) + + return ext_lower + + def _sanitize_filename(self, filename): + """Remove path traversal and dangerous characters from filename""" + if not filename: + raise ValidationError("Filename cannot be empty") + + # Remove path separators and dangerous characters + dangerous_chars = ['/', '\\', '..', '\0', '\n', '\r'] + sanitized = filename + for char in dangerous_chars: + sanitized = sanitized.replace(char, '_') + + # Limit filename length + max_length = 200 + if len(sanitized) > max_length: + sanitized = sanitized[:max_length] + + return sanitized + + def check_length(self): + """ + Validate text length against charmax + """ + if len(self.illusion_text) > self.charmax: + logger.warning( + f"Text length ({len(self.illusion_text)}) exceeds maximum " + f"allowed ({self.charmax}). Truncating to {self.charmax} characters." + ) + self.illusion_text = self.illusion_text[:self.charmax] + + if len(self.illusion_text) == 0: + raise ValidationError("Text cannot be empty after truncation") + + + def draw_clear(self): + + """Create raw image""" + + self.raw_img = Image.new("RGB", + self.img_size_text, + self.background_color) + self.img = Image.new("RGBA", + self.img_size, + self.background_color) + self.circle_img = Image.new("RGBA", + self.img_size, + self.background_color) + self.full_image = Image.new("RGBA", + self.img_size, + self.background_color) + self.draw = ImageDraw.Draw(self.raw_img) + + def estimate_font_size(self): + """ + Rule-based method for arriving at an 'ok' guess for the font size + """ + + size = 0 # in milinches + for s in self.illusion_text: + if s in 'lij|\' ': size += 37 + elif s in '![]fI.,:;/\\t': size += 50 + elif s in '`-(){}r"': size += 60 + elif s in '*^zcsJkvxy': size += 85 + elif s in 'aebdhnopqug#$L+<>=?_~FZT' + digits: size += 95 + elif s in 'BSPEAKVXY&UwNRCHD': size += 112 + elif s in 'QGOMm%W@': size += 135 + else: size += 50 + milinches = size * 6 / 1000.0 + self.font_size_guess = min(max(int(280 - 18.7*milinches), 60), 220) + + def get_fontsize(self): + """ + Find optimal font size using binary search. + + Optimized with binary search for 5-10x speedup (6 iterations vs 60). + + Returns: + tuple: (font_size, bounding_box) + + Raises: + FileOperationError: If font file cannot be loaded + RuntimeError: If font size search fails + """ + def test_font_size(font_size): + """Test if a font size fits within bounds.""" + try: + font = ImageFont.truetype(self.font_path, font_size) + except (IOError, OSError) as e: + logger.warning(f"Cannot load font at size {font_size}: {e}") + return None, None, False + + # Create test image + raw_img = Image.new("RGB", self.img_size_text, self.background_color) + draw = ImageDraw.Draw(raw_img) + draw.text((self.crop_width_x, self.crop_width_y), + self.illusion_text, + self.text_color, + font=font) + + # Find bounding box + inverted = ImageOps.invert(raw_img) + bbox = inverted.getbbox() + if bbox is None: + return None, None, False + + boundingbox = ( + bbox[0] - self.crop_width_x, + bbox[1] - self.crop_width_y, + bbox[2] + self.crop_width_x, + bbox[3] + self.crop_width_y + ) + + # Check if text fits + text_width = boundingbox[2] - boundingbox[0] + max_width = self.img_side - 2 * self.crop_width_x + fits = text_width < max_width + + return font, boundingbox, fits + + try: + # OPTIMIZED: Binary search for optimal font size (5-10x faster!) + min_size = max(self.font_size_guess - 30, 10) + max_size = min(self.font_size_guess + 30, 350) + + best_size = min_size + best_font = None + best_bbox = None + + # Binary search to find largest font that fits + logger.debug(f"Binary search for font size in range [{min_size}, {max_size}]") + iterations = 0 + while min_size <= max_size and iterations < 15: # Limit iterations + iterations += 1 + mid_size = (min_size + max_size) // 2 + + font, bbox, fits = test_font_size(mid_size) + if font is None: + # Font loading failed, try smaller + max_size = mid_size - 1 + continue + + if fits: + # This size fits, try larger + best_size = mid_size + best_font = font + best_bbox = bbox + min_size = mid_size + 1 + else: + # Too large, try smaller + max_size = mid_size - 1 + + # If no valid font found, try with adjusted guess + if best_font is None: + logger.warning(f"No suitable font found in range, retrying with adjusted guess") + self.font_size_guess = max(self.font_size_guess - 20, 20) + # Try one more time with smaller fonts + for size in range(self.font_size_guess, 10, -5): + font, bbox, fits = test_font_size(size) + if font is not None and fits: + best_size = size + best_font = font + best_bbox = bbox + break + + if best_font is None: + raise RuntimeError( + f"Could not find suitable font size for text '{self.illusion_text}'. " + f"Try reducing text length or increasing img_side." + ) + + logger.debug(f"Found optimal font size: {best_size} (in {iterations} iterations)") + self.font_size = best_size + self.font = best_font + self.boundingbox = best_bbox + + return best_size, best_bbox + + except FileNotFoundError as e: + raise FileOperationError(f"Font file not found: {self.font_path}") from e + except PermissionError as e: + raise FileOperationError(f"No permission to read font: {self.font_path}") from e + except (KeyboardInterrupt, SystemExit, MemoryError): + # Never catch these - re-raise immediately + raise + except Exception as e: + logger.error(f"Unexpected error while loading font '{self.font_path}': {type(e).__name__}: {e}") + raise RuntimeError( + f"Error finding font size: {type(e).__name__}" + ) from e + + def draw_frame(self): + """ + Render text frame and apply circular distortion. + + Optimized with NumPy vectorization for 50-100x speedup. + """ + # Start drawing boxes + self.raw_img = Image.new("RGB", + self.img_size_text, + self.background_color) + draw = ImageDraw.Draw(self.raw_img) + draw.text((self.crop_width_x, self.crop_width_y), + self.illusion_text, + self.text_color, + font=self.font) + inverted = ImageOps.invert(self.raw_img) + self.raw_img = self.raw_img.crop(self.boundingbox) + self.scaled_img = self.raw_img.resize((self.img_side, self.img_side), + Image.LANCZOS) # Better quality than BICUBIC + self.img.paste(self.scaled_img, (0, 0)) + + # OPTIMIZED: Vectorized alpha channel and darkness threshold conversion + # Convert to numpy array for vectorized operations (50-100x faster!) + img_array = np.array(self.img, dtype=np.uint8) + + # Create output array with alpha channel + output = np.zeros((img_array.shape[0], img_array.shape[1], 4), dtype=np.uint8) + + # Extract green channel for brightness comparison + brightness = img_array[:, :, 1] + + # Create masks for different conditions + is_light = brightness >= self.darkness_threshold + is_dark = brightness < self.darkness_threshold + + # Apply transformations vectorized (instead of nested loops) + output[is_light] = self.background_color + (0,) # Transparent background + output[is_dark] = self.text_color + (255,) # Opaque text + + # Convert back to PIL Image + self.img = Image.fromarray(output, mode='RGBA') + self.circle_img.paste(self.img, (0, 0)) + + # Stretch text vertically along the path of a circle + # This creates the circular text effect by mapping each column's pixels + # to stretched positions based on the circle's height at that x-coordinate + pixdata = self.img.load() + pixdata2 = self.circle_img.load() + + radius = self.img_side / 2 + + for x in range(self.img_side): + # Calculate the vertical height of the circle at this x position + # Ysize = 2 * sqrt(radius^2 - (x - radius)^2) + distance_from_center = abs(x - radius) + if distance_from_center < radius: + Ysize = 2 * sqrt(radius**2 - distance_from_center**2) + + # Stretch this column vertically to fill the circle height + for y in range(self.img_side): + # Calculate the offset and stretched Y position + Yoffset = int((self.img_side - Ysize) / 2.) + Y = Yoffset + int((Ysize / self.img_side) * y) + + # Map the original pixel to the stretched position + if 0 <= Y < self.img_side: + pixdata2[x, Y] = pixdata[x, y] + + # Create circular mask - make pixels outside circle transparent + if sqrt((x - radius)**2 + (y - radius)**2) >= radius - 2: + pixdata2[x, y] = self.background_color + (0,) + + + def stamp(self): + """ Stamp text repeatedly in a circular manner """ + for i in range(self.num_rotations): + this_circle = self.circle_img.rotate(i*180/self.num_rotations) + self.full_image.paste(this_circle, (0, 0), this_circle) + + + def alpha_to_white(self): + """ + Turn alpha channel back to white. + + Optimized with NumPy vectorization for 50-100x speedup. + """ + # OPTIMIZED: Vectorized alpha channel replacement + img_array = np.array(self.full_image, dtype=np.uint8) + + # Create mask for transparent pixels (alpha channel = 0) + is_transparent = img_array[:, :, 3] == 0 + + # Replace transparent pixels with opaque background color + img_array[is_transparent] = self.background_color + (255,) + + # Convert back to PIL Image + self.full_image = Image.fromarray(img_array, mode='RGBA') + + def save_img(self): + """ Save as png """ + self.full_image.save(self.get_file_path()) + + def get_file_path(self): + """ + Return validated file location. + + Returns: + str: Absolute path to output file + + Raises: + ValidationError: If path traversal is detected or path is invalid + """ + # Determine base directory + if self.file_path == '': + base_path = Path.cwd().resolve() + else: + try: + base_path = Path(self.file_path).resolve() + except (ValueError, OSError) as e: + raise ValidationError(f"Invalid file path: {self.file_path}") from e + + # Sanitize filename + safe_filename = self._sanitize_filename(self.file_name) + + # Create full path + writefile = safe_filename + self.file_ext + handle = base_path / writefile + resolved = handle.resolve() + + # Critical: Ensure the resolved path is within allowed directory + try: + resolved.relative_to(base_path) + except ValueError: + raise ValidationError( + f"Path traversal detected: resolved path '{resolved}' " + f"is outside base directory '{base_path}'" + ) + + # Check if parent directory exists + if not resolved.parent.exists(): + raise ValidationError( + f"Output directory does not exist: {resolved.parent}" + ) + + # Check if parent is actually a directory + if not resolved.parent.is_dir(): + raise ValidationError( + f"Output path parent is not a directory: {resolved.parent}" + ) + + # workaround for https://github.com/python-pillow/Pillow/issues/1747 + return str(resolved) + + def create(self): + """ Perform all steps except initialization """ + self.check_length() + self.estimate_font_size() + self.draw_clear() + self.get_fontsize() + self.draw_frame() + self.stamp() + self.alpha_to_white() + self.save_img() + +def demo(): + foo = Pyedgeon() + foo.check_length() + foo.estimate_font_size() + foo.draw_clear() + foo.get_fontsize() + foo.draw_frame() + foo.stamp() + foo.alpha_to_white() + foo.save_img() + +if __name__ == "__main__": + demo() + diff --git a/scripts/example.py b/scripts/example.py new file mode 100755 index 0000000000000000000000000000000000000000..0726b82eba6cbf1d0a73e6fb1e15a75c8cbf91fe --- /dev/null +++ b/scripts/example.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +""" +Quick-start example for pyedgeon. + +This script demonstrates how to create a simple pyedgeon button +with customizable message, font, and output filename. + +Usage: + python example.py + python example.py "CUSTOM TEXT" + python example.py "CUSTOM TEXT" --font /path/to/font.ttf + python example.py "CUSTOM TEXT" --output my_image.png + +Or via Makefile: + make example + make example MESSAGE="CUSTOM TEXT" +""" + +import argparse +import sys +from pathlib import Path +from pyedgeon import Pyedgeon + + +def main(): + """Create a pyedgeon image with command-line arguments.""" + parser = argparse.ArgumentParser( + description="Create a pyedgeon optical illusion image", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + %(prog)s + %(prog)s "HELLO WORLD" + %(prog)s "SECRET MESSAGE" --font /System/Library/Fonts/Helvetica.ttc + %(prog)s "COOL DESIGN" --output cool.png + """ + ) + + parser.add_argument( + 'message', + nargs='?', + default='HELLO WORLD', + help='Text message to encode in the illusion (default: "HELLO WORLD")' + ) + + parser.add_argument( + '--font', + '--font-path', + dest='font_path', + default=None, + help='Path to TrueType font file (auto-detected if not specified)' + ) + + parser.add_argument( + '--output', + '--output-filename', + dest='output_filename', + default=None, + help='Output filename (default: based on message text)' + ) + + parser.add_argument( + '--size', + '--img-size', + dest='img_size', + type=int, + default=1024, + help='Image size in pixels (default: 1024)' + ) + + parser.add_argument( + '--rotations', + type=int, + default=6, + help='Number of text rotations (default: 6)' + ) + + args = parser.parse_args() + + # Prepare parameters + message = args.message + font_path = args.font_path + img_size = args.img_size + rotations = args.rotations + + # Handle output filename + if args.output_filename: + # Extract filename and extension + output_path = Path(args.output_filename) + file_name = output_path.stem + file_ext = output_path.suffix if output_path.suffix else '.png' + else: + file_name = None # Will use message as filename + file_ext = '.png' + + # Print configuration + print(f"Creating pyedgeon image...") + print(f" Message: {message}") + if font_path: + print(f" Font: {font_path}") + else: + print(f" Font: Auto-detecting system font") + print(f" Image size: {img_size}x{img_size}") + print(f" Rotations: {rotations}") + + try: + # Create the image + img = Pyedgeon( + illusion_text=message, + font_path=font_path, + file_name=file_name, + file_ext=file_ext, + img_side=img_size, + num_rotations=rotations + ) + img.create() + + output_file = img.get_file_path() + print(f"\nSuccess! Image saved to: {output_file}") + print(f"\nTip: View the image on a mobile device or tilt your screen") + print(f" to nearly edge-on to see the hidden message!") + + except Exception as e: + print(f"\nError: {e}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..288314a75342a513d035ca6ef3a81936e2f05e3a --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,11 @@ +""" +Pyedgeon test suite. + +This package contains comprehensive tests for the pyedgeon library including: +- Unit tests for individual methods +- Integration tests for the full pipeline +- Security tests for vulnerability detection +- Performance tests and benchmarks +""" + +__version__ = "1.0.0" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..8554e8e2b30e154930118d17bf3702309f69008d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,195 @@ +""" +Pytest configuration and shared fixtures for pyedgeon test suite. + +This module provides common test fixtures, utilities, and configuration +for all test modules in the pyedgeon test suite. +""" + +import os +import sys +import tempfile +import shutil +from pathlib import Path +import pytest +from PIL import Image + +# Add parent directory to path to import pyedgeon +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from pyedgeon import Pyedgeon + + +@pytest.fixture +def temp_dir(): + """ + Provides a temporary directory for test file outputs. + Automatically cleaned up after test completion. + """ + temp_path = tempfile.mkdtemp() + yield temp_path + # Cleanup after test + if os.path.exists(temp_path): + shutil.rmtree(temp_path) + + +@pytest.fixture +def font_path(): + """ + Provides a path to a TrueType font for testing. + Users must provide their own font file - pyedgeon does not bundle fonts. + + Tests will be skipped if no suitable font is found. + Looks for fonts in common system locations. + """ + # Check common system font locations + possible_fonts = [ + # macOS + "/System/Library/Fonts/Supplemental/Arial.ttf", + "/System/Library/Fonts/Helvetica.ttc", + # Linux + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/liberation/LiberationSans-Regular.ttf", + # Windows + "C:\\Windows\\Fonts\\arial.ttf", + ] + + for font_file in possible_fonts: + if Path(font_file).exists(): + return str(font_file) + + pytest.skip("No suitable system font found for testing. Pyedgeon does not bundle fonts.") + + +@pytest.fixture +def default_pyedgeon(font_path, temp_dir): + """ + Creates a Pyedgeon instance with safe default settings for testing. + Uses the bundled font and a temporary directory. + """ + return Pyedgeon( + illusion_text="TEST", + font_path=font_path, + file_path=temp_dir, + num_rotations=6, + img_side=512 # Smaller for faster tests + ) + + +@pytest.fixture +def minimal_pyedgeon(font_path, temp_dir): + """ + Creates a minimal Pyedgeon instance for quick tests. + Uses smallest viable settings for performance. + """ + return Pyedgeon( + illusion_text="HI", + font_path=font_path, + file_path=temp_dir, + num_rotations=2, + img_side=256 # Very small for speed + ) + + +@pytest.fixture +def sample_colors(): + """ + Provides a set of valid color tuples for testing. + """ + return { + 'black': (0, 0, 0), + 'white': (255, 255, 255), + 'red': (255, 0, 0), + 'green': (0, 255, 0), + 'blue': (0, 0, 255), + 'gray': (128, 128, 128), + } + + +@pytest.fixture +def fake_font_file(temp_dir): + """ + Creates a fake (non-functional) font file for path validation testing. + """ + fake_font = Path(temp_dir) / "fake_font.ttf" + fake_font.write_bytes(b"not a real font") + return str(fake_font) + + +@pytest.fixture +def malicious_paths(): + """ + Provides a collection of potentially malicious file paths for security testing. + """ + return [ + "../../../etc/passwd", + "..\\..\\..\\windows\\system32\\config\\sam", + "/etc/shadow", + "C:\\Windows\\System32\\config\\SAM", + "./../sensitive_data.txt", + "~/../../root/.ssh/id_rsa", + "file:///etc/passwd", + "\x00malicious.txt", # Null byte injection + "normal_path\x00../../etc/passwd", + ] + + +@pytest.fixture +def long_text_samples(): + """ + Provides text samples of various lengths for boundary testing. + """ + return { + 'empty': '', + 'single': 'A', + 'normal': 'HELLO WORLD', + 'max_length': 'A' * 22, + 'over_limit': 'A' * 50, + 'very_long': 'A' * 1000, + } + + +def assert_valid_image(file_path, expected_size=None): + """ + Helper function to assert that a file is a valid image. + + Args: + file_path: Path to the image file + expected_size: Optional tuple (width, height) to verify image dimensions + """ + assert os.path.exists(file_path), f"Image file does not exist: {file_path}" + assert os.path.getsize(file_path) > 0, f"Image file is empty: {file_path}" + + # Try to open with PIL to verify it's a valid image + try: + with Image.open(file_path) as img: + if expected_size: + assert img.size == expected_size, \ + f"Image size {img.size} does not match expected {expected_size}" + # Verify image is not completely blank + extrema = img.convert('L').getextrema() + assert extrema[0] != extrema[1] or extrema[0] != 255, \ + "Image appears to be completely blank" + except Exception as e: + pytest.fail(f"Failed to validate image {file_path}: {e}") + + +def count_pixels_by_color(image, color): + """ + Counts the number of pixels of a specific color in an image. + + Args: + image: PIL Image object + color: Tuple of RGB values + + Returns: + int: Count of pixels matching the color + """ + if image.mode != 'RGB': + image = image.convert('RGB') + + pixels = list(image.getdata()) + return pixels.count(color) + + +# Export helper functions so tests can use them +__all__ = ['assert_valid_image', 'count_pixels_by_color'] diff --git a/tests/requirements-test.txt b/tests/requirements-test.txt new file mode 100644 index 0000000000000000000000000000000000000000..2944b6486c0f0f176483aee7a2a999c5b338cd78 --- /dev/null +++ b/tests/requirements-test.txt @@ -0,0 +1,27 @@ +# Testing dependencies for pyedgeon + +# Core testing framework +pytest>=7.0.0 +pytest-cov>=4.0.0 +pytest-xdist>=3.0.0 # For parallel test execution +pytest-timeout>=2.1.0 # For timeout handling +pytest-benchmark>=4.0.0 # For performance benchmarks + +# Code quality and coverage +coverage>=7.0.0 + +# Image testing and validation +pillow>=9.0.0 # Should match main dependency + +# Mocking and fixtures +pytest-mock>=3.10.0 + +# Testing utilities +pytest-html>=3.1.0 # HTML test reports +pytest-json-report>=1.5.0 # JSON test reports + +# Security testing +safety>=2.3.0 # Dependency vulnerability scanning + +# Additional utilities +colorama>=0.4.6 # Colored terminal output diff --git a/tests/test_image_generation.py b/tests/test_image_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..13457196f576962f0f8d11adfe679215906dd769 --- /dev/null +++ b/tests/test_image_generation.py @@ -0,0 +1,662 @@ +""" +Integration and functional tests for Pyedgeon image generation. + +Tests cover: +- Full image generation pipeline +- Individual method functionality +- Image quality and correctness +- Error conditions +- Edge cases +""" + +import os +import pytest +from pathlib import Path +from PIL import Image +from pyedgeon import Pyedgeon +from .conftest import assert_valid_image + + +class TestImageGeneration: + """Test the complete image generation pipeline.""" + + def test_create_basic_image(self, minimal_pyedgeon): + """Test creating a basic image with minimal settings.""" + p = minimal_pyedgeon + + # Run the full pipeline + p.create() + + # Verify file was created + output_path = p.get_file_path() + assert_valid_image(output_path, expected_size=(p.img_side, p.img_side)) + + def test_create_with_custom_text(self, font_path, temp_dir): + """Test creating image with custom text.""" + custom_text = "TESTING" + p = Pyedgeon( + illusion_text=custom_text, + font_path=font_path, + file_path=temp_dir, + img_side=256 + ) + + p.create() + + output_path = p.get_file_path() + assert_valid_image(output_path) + assert p.illusion_text == custom_text + + def test_create_with_colors(self, font_path, temp_dir, sample_colors): + """Test that custom colors can be used (syntax error fixed).""" + # The key test is that alpha_to_white() no longer has the syntax error + # Full image creation is tested in other tests + p = Pyedgeon( + illusion_text="A", + font_path=font_path, + file_path=temp_dir, + text_color=sample_colors['red'], + background_color=sample_colors['blue'], + img_side=256, + num_rotations=2 + ) + + # Verify colors were set correctly + assert p.text_color == sample_colors['red'] + assert p.background_color == sample_colors['blue'] + + # The syntax error that prevented this from working has been fixed + # (alpha_to_white used to have: self.background_color (255, ) + # instead of: self.background_color + (255, )) + + def test_create_different_sizes(self, font_path, temp_dir): + """Test creating images of different sizes.""" + sizes = [128, 256, 512, 1024] + + for size in sizes: + p = Pyedgeon( + illusion_text="SIZE", + font_path=font_path, + file_path=temp_dir, + file_name=f"size_test_{size}", + img_side=size + ) + + p.create() + + output_path = p.get_file_path() + assert_valid_image(output_path, expected_size=(size, size)) + + def test_create_with_different_rotations(self, font_path, temp_dir): + """Test creating images with different rotation counts.""" + rotations = [2, 4, 6, 8] + + for num_rot in rotations: + p = Pyedgeon( + illusion_text="ROTATE", + font_path=font_path, + file_path=temp_dir, + file_name=f"rotation_test_{num_rot}", + num_rotations=num_rot, + img_side=256 + ) + + p.create() + + output_path = p.get_file_path() + assert_valid_image(output_path) + + def test_create_with_long_text_truncation(self, font_path, temp_dir): + """Test that long text is handled via truncation to charmax.""" + long_text = "THIS IS A VERY LONG TEXT THAT SHOULD BE TRUNCATED" + p = Pyedgeon( + illusion_text=long_text, + font_path=font_path, + file_path=temp_dir, + img_side=256 + ) + + p.create() + + # Text should be truncated to charmax (default is 22, not hardcoded 20) + assert len(p.illusion_text) == 22 + output_path = p.get_file_path() + assert_valid_image(output_path) + + +class TestCheckLength: + """Test the check_length() method.""" + + def test_check_length_within_limit(self, default_pyedgeon): + """Test text within character limit is not truncated.""" + p = default_pyedgeon + p.illusion_text = "SHORT" + original_length = len(p.illusion_text) + + p.check_length() + + assert len(p.illusion_text) == original_length + + def test_check_length_at_limit(self, default_pyedgeon): + """Test text at exactly charmax limit.""" + p = default_pyedgeon + p.charmax = 10 + p.illusion_text = "A" * 10 + + p.check_length() + + assert len(p.illusion_text) == 10 + + def test_check_length_over_limit(self, default_pyedgeon): + """Test text over limit is truncated to charmax (bug fixed).""" + p = default_pyedgeon + p.charmax = 10 + p.illusion_text = "A" * 30 + + p.check_length() + + # Bug fixed: now correctly truncates to charmax instead of hardcoded 20 + assert len(p.illusion_text) == 10 + + # Warning is logged (not printed to stdout) + + def test_check_length_empty_string(self, default_pyedgeon): + """Test check_length with empty string.""" + p = default_pyedgeon + p.illusion_text = "" + + # Empty string now properly raises ValidationError + with pytest.raises(Exception): + p.check_length() + + +class TestEstimateFontSize: + """Test the estimate_font_size() method.""" + + def test_estimate_font_size_basic(self, default_pyedgeon): + """Test basic font size estimation.""" + p = default_pyedgeon + p.illusion_text = "HELLO" + + p.estimate_font_size() + + assert p.font_size_guess is not None + assert isinstance(p.font_size_guess, int) + assert 60 <= p.font_size_guess <= 220 + + def test_estimate_font_size_narrow_chars(self, default_pyedgeon): + """Test font size estimation with narrow characters.""" + p = default_pyedgeon + p.illusion_text = "IIIIII" # Narrow characters + + p.estimate_font_size() + + # Narrow characters should result in larger font size + assert p.font_size_guess is not None + + def test_estimate_font_size_wide_chars(self, default_pyedgeon): + """Test font size estimation with wide characters.""" + p = default_pyedgeon + p.illusion_text = "WWWWWW" # Wide characters + + p.estimate_font_size() + + # Wide characters should result in smaller font size + assert p.font_size_guess is not None + + def test_estimate_font_size_mixed_chars(self, default_pyedgeon): + """Test font size estimation with mixed character widths.""" + p = default_pyedgeon + p.illusion_text = "HELLO WORLD" + + p.estimate_font_size() + + assert p.font_size_guess is not None + assert 60 <= p.font_size_guess <= 220 + + def test_estimate_font_size_digits(self, default_pyedgeon): + """Test font size estimation with digits.""" + p = default_pyedgeon + p.illusion_text = "123456" + + p.estimate_font_size() + + assert p.font_size_guess is not None + + def test_estimate_font_size_special_chars(self, default_pyedgeon): + """Test font size estimation with special characters.""" + p = default_pyedgeon + p.illusion_text = "!@#$%^" + + p.estimate_font_size() + + assert p.font_size_guess is not None + + def test_estimate_font_size_bounds(self, default_pyedgeon): + """Test that estimate_font_size respects min/max bounds.""" + test_cases = [ + ("I" * 50, 60), # Very long narrow text -> minimum 60 + ("W", 220), # Very short wide text -> maximum 220 + ] + + for text, expected_bound in test_cases: + p = default_pyedgeon + p.illusion_text = text + p.estimate_font_size() + + # Should be clamped to bounds + assert 60 <= p.font_size_guess <= 220 + + +class TestDrawClear: + """Test the draw_clear() method.""" + + def test_draw_clear_creates_images(self, default_pyedgeon): + """Test that draw_clear creates all required image objects.""" + p = default_pyedgeon + + p.draw_clear() + + # Verify all image objects are created + assert hasattr(p, 'raw_img') + assert hasattr(p, 'img') + assert hasattr(p, 'circle_img') + assert hasattr(p, 'full_image') + assert hasattr(p, 'draw') + + # Verify they are PIL Image objects + assert isinstance(p.raw_img, Image.Image) + assert isinstance(p.img, Image.Image) + assert isinstance(p.circle_img, Image.Image) + assert isinstance(p.full_image, Image.Image) + + def test_draw_clear_correct_sizes(self, default_pyedgeon): + """Test that draw_clear creates images with correct sizes.""" + p = default_pyedgeon + + p.draw_clear() + + assert p.raw_img.size == p.img_size_text + assert p.img.size == p.img_size + assert p.circle_img.size == p.img_size + assert p.full_image.size == p.img_size + + def test_draw_clear_correct_modes(self, default_pyedgeon): + """Test that draw_clear creates images with correct modes.""" + p = default_pyedgeon + + p.draw_clear() + + assert p.raw_img.mode == "RGB" + assert p.img.mode == "RGBA" + assert p.circle_img.mode == "RGBA" + assert p.full_image.mode == "RGBA" + + def test_draw_clear_background_colors(self, default_pyedgeon): + """Test that images are initialized with background color.""" + p = default_pyedgeon + + p.draw_clear() + + # Check that images start with background color + # Sample a pixel from the center + center_x, center_y = p.img_side // 2, p.img_side // 2 + + raw_pixel = p.raw_img.getpixel((center_x, center_y)) + assert raw_pixel == p.background_color + + img_pixel = p.img.getpixel((center_x, center_y)) + assert img_pixel[:3] == p.background_color + + +class TestGetFontsize: + """Test the get_fontsize() method.""" + + def test_get_fontsize_basic(self, default_pyedgeon): + """Test basic font size calculation.""" + p = default_pyedgeon + p.illusion_text = "TEST" + + p.estimate_font_size() + p.draw_clear() + font_size, boundingbox = p.get_fontsize() + + assert font_size is not None + assert boundingbox is not None + assert p.font_size == font_size + assert p.boundingbox == boundingbox + + def test_get_fontsize_creates_font(self, default_pyedgeon): + """Test that get_fontsize creates font object.""" + p = default_pyedgeon + p.illusion_text = "TEST" + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + + assert hasattr(p, 'font') + assert p.font is not None + + def test_get_fontsize_different_texts(self, default_pyedgeon): + """Test font size calculation with different texts.""" + texts = ["A", "HELLO", "TESTING LONGER"] + + for text in texts: + p = default_pyedgeon + p.illusion_text = text + + p.estimate_font_size() + p.draw_clear() + font_size, _ = p.get_fontsize() + + assert font_size is not None + assert font_size > 0 + + def test_get_fontsize_bounding_box(self, default_pyedgeon): + """Test that bounding box is calculated.""" + p = default_pyedgeon + p.illusion_text = "TEST" + + p.estimate_font_size() + p.draw_clear() + _, boundingbox = p.get_fontsize() + + assert len(boundingbox) == 4 + assert all(isinstance(x, int) for x in boundingbox) + # boundingbox = getbbox() offset by -crop_width, so the left/top edge can + # sit up to crop_width left/above origin depending on the font's side bearing + # (e.g. DejaVu on Linux yields -1). Upper bound stays within the image. + assert -p.crop_width_x <= boundingbox[0] < p.img_side + assert -p.crop_width_y <= boundingbox[1] < p.img_side + + +class TestDrawFrame: + """Test the draw_frame() method.""" + + def test_draw_frame_basic(self, minimal_pyedgeon): + """Test basic frame drawing.""" + p = minimal_pyedgeon + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + + # Verify images are modified + assert p.raw_img is not None + assert p.scaled_img is not None + + def test_draw_frame_creates_scaled_image(self, minimal_pyedgeon): + """Test that draw_frame creates scaled image.""" + p = minimal_pyedgeon + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + + assert hasattr(p, 'scaled_img') + assert p.scaled_img.size == (p.img_side, p.img_side) + + def test_draw_frame_alpha_channel(self, minimal_pyedgeon): + """Test that draw_frame properly handles alpha channel.""" + p = minimal_pyedgeon + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + + # Image should have alpha channel + assert p.img.mode == "RGBA" + + # Some pixels should be transparent (alpha = 0) + pixels = list(p.img.getdata()) + transparent_pixels = [px for px in pixels if px[3] == 0] + assert len(transparent_pixels) > 0 + + +class TestStamp: + """Test the stamp() method.""" + + def test_stamp_basic(self, minimal_pyedgeon): + """Test basic stamping functionality.""" + p = minimal_pyedgeon + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + p.stamp() + + # Verify full_image is modified + assert p.full_image is not None + + def test_stamp_rotation_count(self, font_path, temp_dir): + """Test stamping with different rotation counts.""" + rotation_counts = [2, 4, 6, 8] + + for num_rot in rotation_counts: + p = Pyedgeon( + illusion_text="ROT", + font_path=font_path, + file_path=temp_dir, + num_rotations=num_rot, + img_side=256 + ) + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + p.stamp() + + # Verify image was created + assert p.full_image is not None + + +class TestAlphaToWhite: + """Test the alpha_to_white() method.""" + + def test_alpha_to_white_syntax_error(self, minimal_pyedgeon): + """Test that alpha_to_white works correctly (syntax error fixed).""" + p = minimal_pyedgeon + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + p.stamp() + + # Syntax error has been fixed - should work correctly + p.alpha_to_white() + + # Verify the result + assert p.full_image is not None + + +class TestSaveImg: + """Test the save_img() method.""" + + def test_save_img_creates_file(self, minimal_pyedgeon): + """Test that save_img creates a file.""" + p = minimal_pyedgeon + + # Due to syntax error, we can't run full create() + # This test documents the expected behavior + output_path = p.get_file_path() + assert not os.path.exists(output_path) + + def test_save_img_custom_extension(self, font_path, temp_dir): + """Test saving with custom file extension.""" + extensions = [".png", ".jpg", ".bmp"] + + for ext in extensions: + p = Pyedgeon( + illusion_text="EXT", + font_path=font_path, + file_path=temp_dir, + file_ext=ext, + file_name=f"test_ext_{ext[1:]}", + img_side=256 + ) + + output_path = p.get_file_path() + assert output_path.endswith(ext) + + +class TestGetFilePath: + """Test the get_file_path() method.""" + + def test_get_file_path_with_custom_path(self, font_path, temp_dir): + """Test getting file path with custom directory.""" + p = Pyedgeon( + illusion_text="PATH", + font_path=font_path, + file_path=temp_dir, + file_name="test_file" + ) + + output_path = p.get_file_path() + + # get_file_path() calls Path.resolve(), which canonicalizes 8.3 short + # names on Windows (RUNNER~1 -> runneradmin) and /var -> /private/var on + # macOS. Compare against the resolved temp_dir so the check is portable. + assert os.path.realpath(temp_dir) in output_path + assert "test_file.png" in output_path + + def test_get_file_path_empty_path_uses_cwd(self, font_path): + """Test that empty file_path uses current working directory.""" + p = Pyedgeon( + illusion_text="CWD", + font_path=font_path, + file_path="" + ) + + output_path = p.get_file_path() + + # Should contain current working directory + assert len(output_path) > 0 + + def test_get_file_path_includes_extension(self, font_path, temp_dir): + """Test that file path includes correct extension.""" + extensions = [".png", ".jpg", ".gif"] + + for ext in extensions: + p = Pyedgeon( + illusion_text="EXT", + font_path=font_path, + file_path=temp_dir, + file_ext=ext + ) + + output_path = p.get_file_path() + assert output_path.endswith(ext) + + def test_get_file_path_uses_pathlib(self, font_path, temp_dir): + """Test that get_file_path properly uses pathlib.""" + p = Pyedgeon( + illusion_text="PATHLIB", + font_path=font_path, + file_path=temp_dir, + file_name="test" + ) + + output_path = p.get_file_path() + + # Should be a string (converted from Path) + assert isinstance(output_path, str) + + # Should be a valid path + path_obj = Path(output_path) + assert path_obj.parent.exists() + + +class TestFullPipeline: + """Test the complete image generation pipeline.""" + + def test_demo_function_exists(self): + """Test that demo() function exists and is importable.""" + from pyedgeon.pyedgeon import demo + + assert callable(demo) + + def test_individual_steps_in_sequence(self, minimal_pyedgeon): + """Test running all steps individually in correct sequence.""" + p = minimal_pyedgeon + + # Step 1: Check length + p.check_length() + assert len(p.illusion_text) <= p.charmax + + # Step 2: Estimate font size + p.estimate_font_size() + assert p.font_size_guess is not None + + # Step 3: Draw clear images + p.draw_clear() + assert p.raw_img is not None + + # Step 4: Get font size + p.get_fontsize() + assert p.font_size is not None + + # Step 5: Draw frame + p.draw_frame() + assert p.scaled_img is not None + + # Step 6: Stamp + p.stamp() + assert p.full_image is not None + + # Step 7: Alpha to white (syntax error has been fixed) + p.alpha_to_white() + + # Verify completion + assert p.full_image is not None + + +class TestEdgeCases: + """Test edge cases and boundary conditions.""" + + def test_single_character_text(self, font_path, temp_dir): + """Test with single character text.""" + p = Pyedgeon( + illusion_text="A", + font_path=font_path, + file_path=temp_dir, + img_side=256 + ) + + p.check_length() + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + + assert p.font_size is not None + + def test_maximum_charmax_text(self, font_path, temp_dir): + """Test with text at maximum charmax.""" + max_text = "A" * 22 + p = Pyedgeon( + illusion_text=max_text, + font_path=font_path, + file_path=temp_dir, + charmax=22, + img_side=256 + ) + + p.check_length() + assert len(p.illusion_text) == 22 + + def test_whitespace_only_text(self, font_path, temp_dir): + """Test that whitespace-only text is properly rejected.""" + # Whitespace-only text now properly raises ValidationError during init + with pytest.raises(Exception): + p = Pyedgeon( + illusion_text=" ", + font_path=font_path, + file_path=temp_dir, + img_side=256 + ) diff --git a/tests/test_initialization.py b/tests/test_initialization.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2d115f9f2c74a77e26e480331e46717844a645 --- /dev/null +++ b/tests/test_initialization.py @@ -0,0 +1,382 @@ +""" +Unit tests for Pyedgeon initialization and parameter validation. + +Tests cover: +- Constructor parameter handling +- Default value assignments +- Parameter validation +- Type checking +- Boundary conditions +""" + +import pytest +from pyedgeon import Pyedgeon + + +class TestConstructorDefaults: + """Test that constructor sets appropriate default values.""" + + def test_default_illusion_text(self, font_path, temp_dir): + """Test default illusion text is set and uppercased.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.illusion_text == "HELLO WORLD" + + def test_default_num_rotations(self, font_path, temp_dir): + """Test default number of rotations.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.num_rotations == 6 + + def test_default_file_ext(self, font_path, temp_dir): + """Test default file extension.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.file_ext == ".png" + + def test_default_text_color(self, font_path, temp_dir): + """Test default text color is black.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.text_color == (0, 0, 0) + + def test_default_background_color(self, font_path, temp_dir): + """Test default background color is white.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.background_color == (255, 255, 255) + + def test_default_img_side(self, font_path, temp_dir): + """Test default image side length.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.img_side == 1024 + + def test_default_charmax(self, font_path, temp_dir): + """Test default character maximum.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.charmax == 22 + + def test_default_crop_widths(self, font_path, temp_dir): + """Test default crop width values.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.crop_width_x == 14 + assert p.crop_width_y == 5 + + def test_default_darkness_threshold(self, font_path, temp_dir): + """Test default darkness threshold.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.darkness_threshold == 116 + + def test_default_upper_case(self, font_path, temp_dir): + """Test that upper_case defaults to True.""" + p = Pyedgeon(illusion_text="hello", font_path=font_path, file_path=temp_dir) + assert p.illusion_text == "HELLO" + + +class TestTextHandling: + """Test text parameter handling and transformations.""" + + def test_uppercase_conversion(self, font_path, temp_dir): + """Test that text is converted to uppercase by default.""" + p = Pyedgeon( + illusion_text="hello world", + font_path=font_path, + file_path=temp_dir + ) + assert p.illusion_text == "HELLO WORLD" + + def test_uppercase_disabled(self, font_path, temp_dir): + """Test that upper_case=False preserves original case.""" + p = Pyedgeon( + illusion_text="Hello World", + font_path=font_path, + file_path=temp_dir, + upper_case=False + ) + assert p.illusion_text == "Hello World" + + def test_empty_string(self, font_path, temp_dir): + """Test that empty string is properly rejected.""" + import pytest + # Validation now rejects empty strings + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + illusion_text="", + font_path=font_path, + file_path=temp_dir + ) + + def test_special_characters(self, font_path, temp_dir): + """Test handling of special characters.""" + special_text = "HELLO! @#$%" + p = Pyedgeon( + illusion_text=special_text, + font_path=font_path, + file_path=temp_dir + ) + assert p.illusion_text == special_text + + def test_unicode_characters(self, font_path, temp_dir): + """Test handling of unicode characters.""" + unicode_text = "HELLO \u2665" # Heart symbol + p = Pyedgeon( + illusion_text=unicode_text, + font_path=font_path, + file_path=temp_dir + ) + assert p.illusion_text == unicode_text + + def test_numeric_text(self, font_path, temp_dir): + """Test handling of numeric text.""" + p = Pyedgeon( + illusion_text="123456", + font_path=font_path, + file_path=temp_dir + ) + assert p.illusion_text == "123456" + + +class TestColorParameters: + """Test color parameter validation and handling.""" + + def test_custom_text_color(self, font_path, temp_dir): + """Test setting custom text color.""" + red = (255, 0, 0) + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color=red + ) + assert p.text_color == red + + def test_custom_background_color(self, font_path, temp_dir): + """Test setting custom background color.""" + blue = (0, 0, 255) + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + background_color=blue + ) + assert p.background_color == blue + + def test_grayscale_colors(self, font_path, temp_dir): + """Test grayscale color values.""" + gray = (128, 128, 128) + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color=gray + ) + assert p.text_color == gray + + def test_color_boundaries(self, font_path, temp_dir): + """Test color values at boundaries (0 and 255).""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color=(0, 0, 0), + background_color=(255, 255, 255) + ) + assert p.text_color == (0, 0, 0) + assert p.background_color == (255, 255, 255) + + +class TestFileParameters: + """Test file path and naming parameter handling.""" + + def test_custom_file_name(self, font_path, temp_dir): + """Test setting custom file name.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + file_name="custom_name" + ) + assert p.file_name == "custom_name" + + def test_file_name_defaults_to_text(self, font_path, temp_dir): + """Test that file_name defaults to illusion_text.""" + p = Pyedgeon( + illusion_text="TEST TEXT", + font_path=font_path, + file_path=temp_dir + ) + assert p.file_name == "TEST TEXT" + + def test_custom_file_extension(self, font_path, temp_dir): + """Test setting custom file extension.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + file_ext=".jpg" + ) + assert p.file_ext == ".jpg" + + def test_empty_file_path(self, font_path): + """Test that empty file_path is accepted.""" + p = Pyedgeon(font_path=font_path, file_path="") + assert p.file_path == "" + + def test_custom_file_path(self, font_path, temp_dir): + """Test setting custom file path.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.file_path == temp_dir + + +class TestImageSizeParameters: + """Test image size and dimension parameters.""" + + def test_custom_img_side(self, font_path, temp_dir): + """Test setting custom image side length.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=512 + ) + assert p.img_side == 512 + assert p.img_size == (512, 512) + + def test_small_image_size(self, font_path, temp_dir): + """Test with small image size.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=128 + ) + assert p.img_side == 128 + + def test_large_image_size(self, font_path, temp_dir): + """Test with large image size.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=2048 + ) + assert p.img_side == 2048 + + def test_img_size_tuple_creation(self, font_path, temp_dir): + """Test that img_size tuple is created correctly.""" + side = 800 + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=side + ) + assert p.img_size == (side, side) + assert p.img_size_text == (side, side) + + +class TestRotationParameters: + """Test rotation-related parameters.""" + + def test_custom_num_rotations(self, font_path, temp_dir): + """Test setting custom number of rotations.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + num_rotations=8 + ) + assert p.num_rotations == 8 + + def test_minimum_rotations(self, font_path, temp_dir): + """Test with minimum number of rotations.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + num_rotations=1 + ) + assert p.num_rotations == 1 + + def test_many_rotations(self, font_path, temp_dir): + """Test with many rotations.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + num_rotations=12 + ) + assert p.num_rotations == 12 + + +class TestCropParameters: + """Test crop width parameters.""" + + def test_custom_crop_width_x(self, font_path, temp_dir): + """Test setting custom crop_width_x.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + crop_width_x=20 + ) + assert p.crop_width_x == 20 + + def test_custom_crop_width_y(self, font_path, temp_dir): + """Test setting custom crop_width_y.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + crop_width_y=10 + ) + assert p.crop_width_y == 10 + + def test_zero_crop_widths(self, font_path, temp_dir): + """Test with zero crop widths.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + crop_width_x=0, + crop_width_y=0 + ) + assert p.crop_width_x == 0 + assert p.crop_width_y == 0 + + +class TestDarknessThreshold: + """Test darkness threshold parameter.""" + + def test_custom_darkness_threshold(self, font_path, temp_dir): + """Test setting custom darkness threshold.""" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + darkness_threshold=100 + ) + assert p.darkness_threshold == 100 + + def test_threshold_boundaries(self, font_path, temp_dir): + """Test darkness threshold at boundaries.""" + p_low = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + darkness_threshold=0 + ) + assert p_low.darkness_threshold == 0 + + p_high = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + darkness_threshold=255 + ) + assert p_high.darkness_threshold == 255 + + +class TestInitialState: + """Test the initial state of Pyedgeon object after construction.""" + + def test_font_size_initially_none(self, font_path, temp_dir): + """Test that font_size is None before calculation.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.font_size is None + + def test_font_size_guess_initially_none(self, font_path, temp_dir): + """Test that font_size_guess is None before estimation.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + assert p.font_size_guess is None + + def test_all_required_attributes_exist(self, font_path, temp_dir): + """Test that all expected attributes are set after initialization.""" + p = Pyedgeon(font_path=font_path, file_path=temp_dir) + + required_attrs = [ + 'illusion_text', 'font_path', 'num_rotations', 'file_ext', + 'text_color', 'background_color', 'img_side', 'charmax', + 'file_path', 'font_size_guess', 'crop_width_x', 'crop_width_y', + 'darkness_threshold', 'img_size', 'img_size_text', 'file_name', + 'font_size' + ] + + for attr in required_attrs: + assert hasattr(p, attr), f"Missing attribute: {attr}" diff --git a/tests/test_performance.py b/tests/test_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..27b0220aa43ee212ae555d106c615cade87079a9 --- /dev/null +++ b/tests/test_performance.py @@ -0,0 +1,482 @@ +""" +Performance tests for Pyedgeon library. + +Tests cover: +- Execution time benchmarks +- Memory usage +- Resource limits +- Performance regressions +- Scalability +""" + +import time +import pytest +from pyedgeon import Pyedgeon + + +class TestPerformanceBenchmarks: + """Benchmark tests for various operations.""" + + def test_initialization_performance(self, font_path, temp_dir, benchmark): + """Benchmark Pyedgeon initialization time.""" + def create_instance(): + return Pyedgeon( + illusion_text="BENCHMARK", + font_path=font_path, + file_path=temp_dir, + img_side=512 + ) + + result = benchmark(create_instance) + assert result is not None + + def test_estimate_font_size_performance(self, default_pyedgeon, benchmark): + """Benchmark font size estimation.""" + p = default_pyedgeon + p.illusion_text = "PERFORMANCE TEST" + + result = benchmark(p.estimate_font_size) + assert p.font_size_guess is not None + + def test_check_length_performance(self, default_pyedgeon, benchmark): + """Benchmark check_length operation.""" + p = default_pyedgeon + p.illusion_text = "SHORT TEXT" + + benchmark(p.check_length) + + @pytest.mark.slow + def test_draw_clear_performance(self, default_pyedgeon, benchmark): + """Benchmark draw_clear operation.""" + p = default_pyedgeon + + benchmark(p.draw_clear) + assert p.raw_img is not None + + @pytest.mark.slow + def test_get_fontsize_performance(self, minimal_pyedgeon, benchmark): + """Benchmark get_fontsize operation.""" + p = minimal_pyedgeon + p.illusion_text = "PERF" + + p.estimate_font_size() + p.draw_clear() + + result = benchmark(p.get_fontsize) + assert result is not None + + @pytest.mark.slow + def test_full_create_performance_small(self, font_path, temp_dir): + """Benchmark full create() for small image.""" + p = Pyedgeon( + illusion_text="SMALL", + font_path=font_path, + file_path=temp_dir, + file_name="perf_small", + img_side=256, + num_rotations=2 + ) + + start = time.time() + + # Note: Will fail due to syntax error, but measures time to failure + try: + p.create() + except TypeError: + pass # Expected due to line 215 syntax error + + elapsed = time.time() - start + + # Should complete (or fail) in reasonable time + assert elapsed < 10.0, f"Small image took {elapsed:.2f}s, expected < 10s" + + @pytest.mark.slow + def test_full_create_performance_medium(self, font_path, temp_dir): + """Benchmark full create() for medium image.""" + p = Pyedgeon( + illusion_text="MEDIUM", + font_path=font_path, + file_path=temp_dir, + file_name="perf_medium", + img_side=512, + num_rotations=4 + ) + + start = time.time() + + try: + p.create() + except TypeError: + pass # Expected due to line 215 syntax error + + elapsed = time.time() - start + + # Medium images should still be reasonably fast + assert elapsed < 30.0, f"Medium image took {elapsed:.2f}s, expected < 30s" + + +class TestScalability: + """Test performance scaling with different parameters.""" + + @pytest.mark.slow + def test_scaling_with_text_length(self, font_path, temp_dir): + """Test performance scaling with text length. + + Marked slow: this is a wall-clock ratio benchmark. Baselines here sit at + the clock-resolution/jitter floor on shared CI runners, so it runs only + in the full (single-OS) suite, not the multi-OS fast matrix. + """ + text_lengths = [5, 10, 15, 20] + times = [] + + for length in text_lengths: + text = "A" * length + p = Pyedgeon( + illusion_text=text, + font_path=font_path, + file_path=temp_dir, + img_side=256 + ) + + start = time.perf_counter() + p.estimate_font_size() + elapsed = time.perf_counter() - start + + times.append(elapsed) + + # Font size estimation should scale roughly linearly; verify it doesn't + # explode exponentially. Floor the baseline: estimate_font_size() is fast + # enough that timings approach the clock resolution (time.time() reads + # 0.0 on Windows), which would make the ratio meaningless. + baseline = max(times[0], 1e-4) + assert times[-1] < baseline * 10, "Performance degradation too severe" + + def test_scaling_with_image_size(self, font_path, temp_dir): + """Test performance scaling with image size.""" + sizes = [128, 256, 512] + times = [] + + for size in sizes: + p = Pyedgeon( + illusion_text="SCALE", + font_path=font_path, + file_path=temp_dir, + img_side=size + ) + + start = time.time() + p.draw_clear() + elapsed = time.time() - start + + times.append(elapsed) + + # Image creation should scale roughly quadratically with size + # (pixels increase as size^2) + for t in times: + assert t < 5.0, f"Image creation took {t:.2f}s, too slow" + + @pytest.mark.slow + def test_scaling_with_num_rotations(self, font_path, temp_dir): + """Test performance scaling with number of rotations. + + Marked slow: wall-clock ratio benchmark with a sub-millisecond baseline, + which is dominated by scheduler jitter on shared CI runners. Runs in the + full (single-OS) suite, not the multi-OS fast matrix. + """ + rotation_counts = [2, 4, 6, 8] + times = [] + + for num_rot in rotation_counts: + p = Pyedgeon( + illusion_text="ROT", + font_path=font_path, + file_path=temp_dir, + num_rotations=num_rot, + img_side=256 + ) + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + + start = time.perf_counter() + p.stamp() + elapsed = time.perf_counter() - start + + times.append(elapsed) + + # Stamping should scale linearly with rotations. Floor the baseline: + # stamp() can finish below the clock resolution (time.time() reads 0.0 on + # Windows), collapsing the RHS to 0 and failing spuriously. + baseline = max(times[0], 1e-4) + assert times[-1] < baseline * (rotation_counts[-1] / rotation_counts[0]) * 2 + + +class TestNestedLoopPerformance: + """Test performance of nested pixel loops (known O(n²) issue).""" + + @pytest.mark.slow + def test_draw_frame_nested_loops(self, font_path, temp_dir): + """Test nested loop performance in draw_frame.""" + sizes = [128, 256, 512] + times = [] + + for size in sizes: + p = Pyedgeon( + illusion_text="LOOP", + font_path=font_path, + file_path=temp_dir, + img_side=size + ) + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + + start = time.time() + p.draw_frame() + elapsed = time.time() - start + + times.append((size, elapsed)) + + # Verify quadratic scaling (or worse) + # Time should increase by ~4x when size doubles + for i in range(len(times) - 1): + size_ratio = times[i+1][0] / times[i][0] + time_ratio = times[i+1][1] / max(times[i][1], 0.001) # Avoid div by 0 + + # With nested loops, expect O(n²) scaling + # So doubling size should ~4x the time (but allow some overhead) + assert time_ratio < size_ratio ** 3, \ + f"Performance worse than O(n²): {time_ratio} for {size_ratio}x size" + + @pytest.mark.slow + def test_alpha_to_white_nested_loops(self, font_path, temp_dir): + """Test nested loop performance in alpha_to_white.""" + # Note: This will fail due to syntax error, but we can still + # test the structure + + sizes = [128, 256] + times = [] + + for size in sizes: + p = Pyedgeon( + illusion_text="ALPHA", + font_path=font_path, + file_path=temp_dir, + img_side=size + ) + + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + p.stamp() + + start = time.time() + try: + p.alpha_to_white() + except TypeError: + pass # Expected syntax error + elapsed = time.time() - start + + times.append((size, elapsed)) + + # Even with the error, we measure the time to reach the error + # Shows the nested loop overhead before hitting the bug + + +class TestFontSizeDiscoveryPerformance: + """Test performance of font size discovery algorithm.""" + + @pytest.mark.slow + def test_get_fontsize_temporary_images(self, minimal_pyedgeon): + """Test that get_fontsize creates many temporary images.""" + p = minimal_pyedgeon + p.illusion_text = "FONT TEST" + + p.estimate_font_size() + p.draw_clear() + + # The algorithm tries 60 font sizes (guess-30 to guess+30) + # Each creates a temporary image + start = time.time() + p.get_fontsize() + elapsed = time.time() - start + + # Should complete but documents the inefficiency + # Creating 60 images is wasteful + assert elapsed < 5.0, f"Font size discovery too slow: {elapsed:.2f}s" + + def test_get_fontsize_recursion_count(self, font_path, temp_dir): + """Test that get_fontsize can recurse multiple times.""" + # With wrong initial guess, it will recurse + # Each recursion tries 60 more font sizes + + p = Pyedgeon( + illusion_text="RECURSION", + font_path=font_path, + file_path=temp_dir, + img_side=256 + ) + + # Manually set a bad guess to force recursion + p.estimate_font_size() + p.draw_clear() + p.font_size_guess = 10 # Too small, will recurse + + start = time.time() + + # This might recurse several times + # Note: Could potentially recurse indefinitely! + try: + with pytest.raises(RecursionError): + # Set Python recursion limit low to catch unbounded recursion + import sys + old_limit = sys.getrecursionlimit() + sys.setrecursionlimit(100) + + p.get_fontsize() + + sys.setrecursionlimit(old_limit) + except: + # If it doesn't hit recursion limit, that's okay + # But it's still inefficient + pass + + elapsed = time.time() - start + + # Should not take forever + assert elapsed < 10.0 + + +class TestMemoryUsage: + """Test memory usage patterns.""" + + def test_multiple_image_objects(self, default_pyedgeon): + """Test that multiple image objects are created.""" + p = default_pyedgeon + + p.draw_clear() + + # Documents that 4 separate images are created (default 512x512) + # This is ~4MB of memory (512*512*4 channels*4 images) + images = [p.raw_img, p.img, p.circle_img, p.full_image] + + for img in images: + assert img.size == (p.img_side, p.img_side) + # Each image uses significant memory + + @pytest.mark.slow + def test_memory_with_large_image(self, font_path, temp_dir): + """Test memory usage with large images.""" + # Large image uses substantial memory + large_size = 2048 + + p = Pyedgeon( + illusion_text="MEMORY", + font_path=font_path, + file_path=temp_dir, + img_side=large_size + ) + + # Creating the images allocates memory + p.draw_clear() + + # 4 images * 2048*2048 pixels * 4 bytes/pixel = ~64MB + assert p.img.size == (large_size, large_size) + + +class TestResourceLimits: + """Test behavior at resource limits.""" + + def test_unrestricted_image_size(self, font_path, temp_dir): + """Test that image size is now properly restricted.""" + # Validation now prevents huge sizes (max is 8192) + + huge_size = 50000 # Would create 50000x50000 = 2.5B pixels + + # Validation now properly rejects this + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + illusion_text="HUGE", + font_path=font_path, + file_path=temp_dir, + img_side=huge_size + ) + + def test_unrestricted_text_length(self, font_path, temp_dir): + """Test that text length is now properly restricted.""" + # Validation now prevents very long text (max is 10000) + + very_long = "A" * 100000 + + # Validation now properly rejects this + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + illusion_text=very_long, + font_path=font_path, + file_path=temp_dir + ) + + def test_unrestricted_num_rotations(self, font_path, temp_dir): + """Test that num_rotations is now properly restricted.""" + # Validation now prevents excessive rotations (max is 360) + + excessive = 10000 + + # Validation now properly rejects this + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + illusion_text="ROT", + font_path=font_path, + file_path=temp_dir, + num_rotations=excessive + ) + + +class TestRegression: + """Regression tests for performance improvements.""" + + @pytest.mark.slow + def test_baseline_small_image(self, font_path, temp_dir): + """Baseline performance test for small images.""" + p = Pyedgeon( + illusion_text="BASELINE", + font_path=font_path, + file_path=temp_dir, + file_name="baseline_test", + img_side=256, + num_rotations=2 + ) + + start = time.time() + + # Run through all steps up to the syntax error + p.check_length() + p.estimate_font_size() + p.draw_clear() + p.get_fontsize() + p.draw_frame() + p.stamp() + + elapsed = time.time() - start + + # Baseline: should complete in under 5 seconds + assert elapsed < 5.0, \ + f"Baseline performance regression: {elapsed:.2f}s (expected < 5s)" + + # Store result for comparison in future test runs + print(f"\nBaseline performance: {elapsed:.2f}s for 256x256 image") + + +# Pytest benchmark plugin integration +pytest_plugins = ['pytest-benchmark'] + + +def pytest_configure(config): + """Configure custom markers.""" + config.addinivalue_line( + "markers", "slow: marks tests as slow (deselect with '-m \"not slow\"')" + ) diff --git a/tests/test_security.py b/tests/test_security.py new file mode 100644 index 0000000000000000000000000000000000000000..db497130dcf02d996a733b7b62ecd1054310e24e --- /dev/null +++ b/tests/test_security.py @@ -0,0 +1,484 @@ +""" +Security tests for Pyedgeon library. + +Tests cover: +- Path traversal vulnerabilities +- Input validation +- Resource exhaustion protection +- File system security +- Injection attacks +""" + +import os +import pytest +from pathlib import Path +from pyedgeon import Pyedgeon + + +class TestPathTraversalPrevention: + """Test protection against path traversal attacks.""" + + def test_file_path_traversal_parent_directory(self, font_path, temp_dir): + """Test that parent directory traversal in file_path is handled safely.""" + malicious_path = "../../../etc" + p = Pyedgeon( + font_path=font_path, + file_path=malicious_path, + illusion_text="TEST" + ) + + # Validation now properly checks that output directory exists + # This will raise an error because ../../../etc likely doesn't exist + with pytest.raises(Exception): # Should raise ValidationError + output_path = p.get_file_path() + + def test_file_path_absolute_system_path(self, font_path, temp_dir): + """Test that absolute system paths in file_path are accepted.""" + # This tests whether the code accepts absolute paths to system directories + # Note: Users may legitimately want to write to specific absolute paths + malicious_paths = [ + "/etc", + "/tmp/../etc", + "/var/log" + ] + + for mal_path in malicious_paths: + p = Pyedgeon( + font_path=font_path, + file_path=mal_path, + illusion_text="TEST" + ) + # Absolute paths are accepted (users may have legitimate use cases) + assert p.file_path == mal_path + + def test_file_name_with_path_traversal(self, font_path, temp_dir): + """Test that file_name with path traversal is properly sanitized.""" + malicious_names = [ + "../../../etc/passwd", + "..\\..\\..\\windows\\system32\\config\\sam", + "./../../secret.txt" + ] + + for mal_name in malicious_names: + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + file_name=mal_name, + illusion_text="TEST" + ) + output_path = p.get_file_path() + + # Verify dangerous characters are sanitized + # Path separators and dots should be removed or replaced + assert "../" not in output_path + assert "..\\" not in output_path + # Should still be within temp_dir (realpath resolves Windows 8.3 + # short names and macOS /var -> /private/var so the compare is portable) + resolved_temp = os.path.realpath(temp_dir) + assert resolved_temp in output_path or output_path.startswith(resolved_temp) + + def test_font_path_traversal(self, temp_dir): + """Test that font_path rejects paths with invalid extensions.""" + malicious_font_paths = [ + "../../../etc/passwd", + "/etc/shadow", + "C:\\Windows\\System32\\config\\SAM" + ] + + for mal_path in malicious_font_paths: + # Font path validation now rejects non-font file extensions + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=mal_path, + file_path=temp_dir, + illusion_text="TEST" + ) + + def test_null_byte_injection_file_name(self, font_path, temp_dir): + """Test handling of null byte injection in file names.""" + malicious_name = "safe_name\x00../../etc/passwd" + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + file_name=malicious_name, + illusion_text="TEST" + ) + # Documents that null bytes are currently not filtered + assert "\x00" in p.file_name + + def test_symlink_in_file_path(self, font_path, temp_dir): + """Test behavior when file_path contains symlinks.""" + # Create a symlink to a different directory + symlink_path = Path(temp_dir) / "symlink" + target_path = Path(temp_dir) / "target" + target_path.mkdir(exist_ok=True) + + try: + symlink_path.symlink_to(target_path) + + p = Pyedgeon( + font_path=font_path, + file_path=str(symlink_path), + illusion_text="TEST" + ) + + # Verify symlinks are followed (current behavior) + assert p.file_path == str(symlink_path) + except OSError: + # Symlink creation might fail on some systems + pytest.skip("Symlink creation not supported") + + +class TestInputValidation: + """Test validation of user inputs.""" + + def test_color_validation_out_of_range_high(self, font_path, temp_dir): + """Test that colors above 255 are properly rejected.""" + # Validation now properly checks color ranges + invalid_color = (300, 300, 300) + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color=invalid_color + ) + + def test_color_validation_negative(self, font_path, temp_dir): + """Test that negative color values are properly rejected.""" + invalid_color = (-10, -20, -30) + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color=invalid_color + ) + + def test_color_validation_wrong_type(self, font_path, temp_dir): + """Test that wrong color type is properly rejected.""" + # Validation now checks that color is a 3-tuple + with pytest.raises(Exception): # Should raise ValidationError or TypeError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color="red" # String instead of tuple + ) + + def test_color_validation_wrong_tuple_length(self, font_path, temp_dir): + """Test that wrong tuple length for color is properly rejected.""" + invalid_colors = [ + (255,), # Too short + (255, 255), # Too short + (255, 255, 255, 255), # Too long + ] + + for invalid_color in invalid_colors: + # Validation now properly checks tuple length + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + text_color=invalid_color + ) + + def test_num_rotations_negative(self, font_path, temp_dir): + """Test that negative num_rotations is properly rejected.""" + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + num_rotations=-5 + ) + + def test_num_rotations_zero(self, font_path, temp_dir): + """Test that zero num_rotations is properly rejected.""" + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + num_rotations=0 + ) + + def test_img_side_negative(self, font_path, temp_dir): + """Test that negative img_side is properly rejected.""" + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=-100 + ) + + def test_img_side_zero(self, font_path, temp_dir): + """Test that zero img_side is properly rejected.""" + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=0 + ) + + def test_charmax_negative(self, font_path, temp_dir): + """Test that negative charmax is properly rejected.""" + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + charmax=-10 + ) + + def test_darkness_threshold_out_of_range(self, font_path, temp_dir): + """Test that darkness_threshold outside 0-255 is properly rejected.""" + invalid_thresholds = [-10, 300, 1000] + + for threshold in invalid_thresholds: + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + darkness_threshold=threshold + ) + + +class TestResourceExhaustion: + """Test protection against resource exhaustion attacks.""" + + def test_extremely_large_image_size(self, font_path, temp_dir): + """Test that extremely large image sizes are properly rejected.""" + # An attacker could try to exhaust memory with huge images + huge_size = 100000 # 100k x 100k = 10 billion pixels + + # Validation now prevents resource exhaustion (max is 8192) + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + img_side=huge_size, + illusion_text="A" + ) + + def test_extremely_long_text(self, font_path, temp_dir): + """Test that extremely long text (>10000 chars) is properly rejected.""" + # Test with very long text that could cause performance issues + long_text = "A" * 10001 # Just over the 10000 limit + + # Validation now rejects text over 10000 characters + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + illusion_text=long_text + ) + + def test_check_length_truncation_silent(self, font_path, temp_dir): + """Test that check_length() correctly truncates text to charmax.""" + long_text = "A" * 50 + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + illusion_text=long_text, + charmax=22 + ) + + p.check_length() + + # Verify text was correctly truncated to charmax (bug has been fixed!) + assert len(p.illusion_text) == 22 + + # Warning is logged (not printed to stdout) + + def test_check_length_hardcoded_truncation(self, font_path, temp_dir): + """Test that truncation correctly uses charmax value (bug fixed).""" + long_text = "A" * 50 + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + illusion_text=long_text, + charmax=30 # Set to 30 + ) + + p.check_length() + + # Bug has been fixed: now correctly truncates to charmax value + assert len(p.illusion_text) == 30 + + def test_many_rotations_performance(self, font_path, temp_dir): + """Test that excessive rotations are properly limited.""" + excessive_rotations = 1000 + + # Validation now prevents excessive rotations (max is 360) + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + num_rotations=excessive_rotations, + illusion_text="A" + ) + + +class TestFileSystemSecurity: + """Test file system security issues.""" + + def test_file_overwrite_without_warning(self, font_path, temp_dir): + """Test that existing files are overwritten without warning.""" + file_name = "test_file" + file_path = Path(temp_dir) / f"{file_name}.png" + + # Create an existing file + file_path.write_text("existing content") + assert file_path.exists() + + # Create Pyedgeon instance that will overwrite + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + file_name=file_name, + illusion_text="TEST" + ) + + # Verify it would overwrite (without actually running create()). + # get_file_path() resolves the path, so canonicalize the expected path + # too (Windows 8.3 short names, macOS /var -> /private/var). + result_path = p.get_file_path() + resolved_file = os.path.realpath(str(file_path)) + assert resolved_file == result_path + + def test_file_extension_validation(self, font_path, temp_dir): + """Test that dangerous file extensions are properly rejected.""" + dangerous_extensions = [ + ".exe", + ".sh", + ".bat", + ".ps1", + "", # No extension + ".png.exe", # Double extension + ] + + for ext in dangerous_extensions: + # Validation now properly rejects dangerous extensions + with pytest.raises(Exception): # Should raise ValidationError + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + file_ext=ext, + illusion_text="TEST" + ) + + def test_font_file_existence_check(self, temp_dir): + """Test that non-existent font files are accepted during init.""" + non_existent_font = "/path/to/nonexistent/font.ttf" + + # Constructor accepts non-existent paths + p = Pyedgeon( + font_path=non_existent_font, + file_path=temp_dir, + illusion_text="TEST" + ) + + assert p.font_path == non_existent_font + + def test_font_file_type_validation(self, temp_dir, fake_font_file): + """Test that non-font files with .ttf extension are accepted.""" + # fake_font_file is not a valid font but has .ttf extension + p = Pyedgeon( + font_path=fake_font_file, + file_path=temp_dir, + illusion_text="TEST" + ) + + # Both point to the same file; realpath canonicalizes them (Windows 8.3 + # short names, macOS /var -> /private/var) so the compare is portable. + assert os.path.realpath(fake_font_file) == os.path.realpath(p.font_path) + + +class TestErrorHandling: + """Test error handling and exception management.""" + + def test_bare_except_in_get_fontsize(self, font_path, temp_dir): + """Test that bare except clause has been fixed in get_fontsize().""" + # Previously had a bare except clause which is a security risk + # Now properly uses specific exception handling + + import inspect + from pyedgeon import Pyedgeon + + source = inspect.getsource(Pyedgeon.get_fontsize) + + # Verify bare except has been fixed - should use 'except Exception as e:' instead + assert "except Exception as e:" in source or "except (IOError, OSError)" in source + # Should NOT have bare except: + assert "except:" not in source or "except Exception" in source # Allow 'except Exception' + + def test_unbounded_recursion_in_get_fontsize(self, font_path, temp_dir): + """Test that get_fontsize() has unbounded recursion.""" + # The function can recurse indefinitely without a base case + # This is a potential denial of service vector + + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + illusion_text="TEST", + img_side=256 + ) + + # Set up conditions that would cause recursion + p.font_size_guess = 50 + + # Note: We don't actually call this to avoid stack overflow + # This test documents the risk + assert hasattr(p, 'get_fontsize') + + +class TestSyntaxErrorDocumentation: + """Document the syntax error on line 215.""" + + def test_line_215_syntax_error_exists(self): + """Test that verifies the syntax error on line 215 has been fixed.""" + # Line 215 previously had: self.background_color (255, ) + # Now correctly fixed to: self.background_color + (255, ) + + import inspect + from pyedgeon import Pyedgeon + + source = inspect.getsource(Pyedgeon.alpha_to_white) + + # Verify the fix is in place - should use + operator, not function call + assert "self.background_color + (255," in source + + +class TestInjectionVectors: + """Test for various injection attack vectors.""" + + def test_command_injection_in_file_path(self, font_path): + """Test that command injection in file_path is possible.""" + # Potentially dangerous path with shell metacharacters + dangerous_paths = [ + "; rm -rf /", + "$(malicious_command)", + "`malicious_command`", + "| cat /etc/passwd", + ] + + for dangerous_path in dangerous_paths: + p = Pyedgeon( + font_path=font_path, + file_path=dangerous_path, + illusion_text="TEST" + ) + # Currently no sanitization + assert dangerous_path in p.file_path + + def test_format_string_in_text(self, font_path, temp_dir): + """Test handling of format string-like text.""" + format_strings = [ + "{0}", + "%s%s%s%s", + "${malicious}", + ] + + for fmt_str in format_strings: + p = Pyedgeon( + font_path=font_path, + file_path=temp_dir, + illusion_text=fmt_str + ) + # Verify format strings are not interpreted + assert p.illusion_text == fmt_str.upper()