import os import torch from transformers import AutoTokenizer, AutoModelForCausalLM import logging import psutil import re import gc import random from typing import List, Dict, Any # Initialize logger logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) # List of memory-optimized models MEMORY_OPTIMIZED_MODELS = [ "gpt2", # ~500MB "distilgpt2", # ~250MB "microsoft/DialoGPT-small", # ~250MB "huggingface/CodeBERTa-small-v1", # Code tasks ] # Singleton state _generator_instance = None # Enhanced pattern matching for comprehensive test case generation REQUIREMENT_PATTERNS = { 'authentication': { 'keywords': ['login', 'authentication', 'signin', 'sign in', 'password', 'username', 'credential', 'auth'], 'priority': 'High', 'category': 'Security' }, 'authorization': { 'keywords': ['permission', 'role', 'access', 'privilege', 'authorize', 'admin', 'user level'], 'priority': 'High', 'category': 'Security' }, 'data_validation': { 'keywords': ['validate', 'validation', 'input', 'format', 'check', 'verify', 'constraint'], 'priority': 'High', 'category': 'Functional' }, 'database': { 'keywords': ['database', 'db', 'store', 'save', 'persist', 'record', 'data storage', 'crud'], 'priority': 'Medium', 'category': 'Functional' }, 'performance': { 'keywords': ['performance', 'speed', 'time', 'response', 'load', 'concurrent', 'scalability'], 'priority': 'Medium', 'category': 'Performance' }, 'ui_interface': { 'keywords': ['interface', 'ui', 'user interface', 'display', 'screen', 'form', 'button', 'menu'], 'priority': 'Medium', 'category': 'UI/UX' }, 'api': { 'keywords': ['api', 'endpoint', 'service', 'request', 'response', 'rest', 'http'], 'priority': 'High', 'category': 'Integration' }, 'error_handling': { 'keywords': ['error', 'exception', 'failure', 'invalid', 'incorrect', 'wrong'], 'priority': 'High', 'category': 'Error Handling' }, 'reporting': { 'keywords': ['report', 'export', 'generate', 'analytics', 'dashboard', 'chart'], 'priority': 'Medium', 'category': 'Reporting' }, 'security': { 'keywords': ['security', 'encrypt', 'secure', 'ssl', 'https', 'token', 'session'], 'priority': 'High', 'category': 'Security' } } def get_optimal_model_for_memory(): """Select the best model based on available memory.""" available_memory = psutil.virtual_memory().available / (1024 * 1024) # MB logger.info(f"Available memory: {available_memory:.1f}MB") if available_memory < 300: return None # Use template fallback elif available_memory < 600: return "microsoft/DialoGPT-small" else: return "distilgpt2" def load_model_with_memory_optimization(model_name): """Load model with low memory settings.""" try: logger.info(f"Loading {model_name} with memory optimizations...") tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side='left', use_fast=True) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype=torch.float16, device_map="cpu", low_cpu_mem_usage=True, use_cache=False, ) model.eval() model.gradient_checkpointing_enable() logger.info(f"✅ Model {model_name} loaded successfully") return tokenizer, model except Exception as e: logger.error(f"❌ Failed to load model {model_name}: {e}") return None, None def analyze_requirements(text: str) -> Dict[str, Any]: """Analyze requirements text to identify patterns and generate appropriate test cases""" text_lower = text.lower() detected_patterns = {} for pattern_name, pattern_info in REQUIREMENT_PATTERNS.items(): matches = [] for keyword in pattern_info['keywords']: if keyword in text_lower: # Find context around the keyword pattern = rf'.{{0,50}}{re.escape(keyword)}.{{0,50}}' context_matches = re.findall(pattern, text_lower, re.IGNORECASE) matches.extend(context_matches) if matches: detected_patterns[pattern_name] = { 'matches': matches[:3], # Limit to 3 matches 'priority': pattern_info['priority'], 'category': pattern_info['category'] } return detected_patterns def generate_authentication_tests(matches: List[str]) -> List[Dict]: """Generate comprehensive authentication test cases""" base_tests = [ { "title": "Valid User Login", "description": "Verify that users can successfully log in with valid credentials", "preconditions": ["User account exists", "Application is accessible"], "steps": [ "Navigate to login page", "Enter valid username", "Enter valid password", "Click login button" ], "expected": "User is successfully authenticated and redirected to dashboard/home page", "postconditions": ["User session is created", "User is logged in"], "test_data": "Valid username: testuser@example.com, Valid password: Test@123" }, { "title": "Invalid Username Login", "description": "Verify that login fails with invalid username", "preconditions": ["Application is accessible"], "steps": [ "Navigate to login page", "Enter invalid/non-existent username", "Enter valid password format", "Click login button" ], "expected": "Login fails with appropriate error message 'Invalid credentials'", "postconditions": ["User remains on login page", "Account security maintained"], "test_data": "Valid username: testuser@example.com, Invalid password: WrongPass123" }, { "title": "Empty Fields Login Attempt", "description": "Verify validation when login attempted with empty fields", "preconditions": ["Application is accessible"], "steps": [ "Navigate to login page", "Leave username field empty", "Leave password field empty", "Click login button" ], "expected": "Validation errors displayed for required fields", "postconditions": ["User remains on login page", "Form validation active"], "test_data": "Username: (empty), Password: (empty)" }, { "title": "SQL Injection Attack Prevention", "description": "Verify that login form prevents SQL injection attacks", "preconditions": ["Application is accessible"], "steps": [ "Navigate to login page", "Enter SQL injection payload in username field", "Enter any password", "Click login button" ], "expected": "Login fails safely without database compromise or error exposure", "postconditions": ["System security maintained", "No unauthorized access"], "test_data": "Username: admin'; DROP TABLE users; --, Password: anypass" } ] return base_tests def generate_data_validation_tests(matches: List[str]) -> List[Dict]: """Generate comprehensive data validation test cases""" return [ { "title": "Valid Data Input Validation", "description": "Verify system accepts valid data formats correctly", "preconditions": ["Form/API endpoint is accessible", "User has appropriate permissions"], "steps": [ "Access the input form/endpoint", "Enter data in valid format", "Submit the form/request", "Verify data is accepted" ], "expected": "Data is accepted and processed successfully with confirmation message", "postconditions": ["Data is stored correctly", "User receives success feedback"], "test_data": "Valid email: user@domain.com, Valid phone: +1-234-567-8900" }, { "title": "Invalid Data Format Rejection", "description": "Verify system rejects invalid data formats", "preconditions": ["Form/API endpoint is accessible"], "steps": [ "Access the input form/endpoint", "Enter data in invalid format", "Submit the form/request", "Verify validation error is shown" ], "expected": "System rejects invalid data with clear error message", "postconditions": ["Invalid data is not stored", "User guided to correct format"], "test_data": "Invalid email: notanemail, Invalid phone: 123-abc-defg" }, { "title": "Boundary Value Testing", "description": "Test data validation at boundary values", "preconditions": ["System has defined data length/value limits"], "steps": [ "Test with minimum allowed value", "Test with maximum allowed value", "Test with value just below minimum", "Test with value just above maximum" ], "expected": "Min/max values accepted, out-of-range values rejected appropriately", "postconditions": ["Boundary validation working correctly"], "test_data": "Min: 1, Max: 100, Below: 0, Above: 101" }, { "title": "Special Characters Handling", "description": "Verify proper handling of special characters in input", "preconditions": ["Input fields accept text data"], "steps": [ "Enter text with special characters (!@#$%^&*)", "Enter text with unicode characters (émañ)", "Enter text with HTML tags (