Source code for mindroot.coreplugins.l8n.test_l8n_standalone
#!/usr/bin/env python3"""Standalone test script for the l8n localization plugin.This script tests the core functionality without MindRoot dependencies."""importasyncioimportosimportrefrompathlibimportPath# Simulate the command decorator for testing
# Copy the core functions from mod.py without MindRoot dependenciesTRANSLATIONS={}LOCALIZED_FILES_DIR=Path(__file__).parent/"localized_files"
[docs]defextract_plugin_root(absolute_path:str)->str:"""Extract the plugin root from an absolute path."""path=Path(absolute_path)parts=path.parts# Find coreplugins in the pathif'coreplugins'inparts:coreplugins_idx=parts.index('coreplugins')ifcoreplugins_idx+1<len(parts):return'/'.join(parts[coreplugins_idx+1:])# Find src/[plugin_name] pattern for external pluginsfori,partinenumerate(parts):ifpart=='src'andi+1<len(parts):potential_plugin=parts[i+1]ifi+2<len(parts):# Has more path after src/plugin_namereturn'/'.join(parts[i+1:])# Fallback: return the filenamereturnpath.name
[docs]defget_localized_file_path(original_path:str)->Path:"""Convert an original file path to its localized version path."""plugin_root=extract_plugin_root(original_path)path=Path(plugin_root)# Determine if this is a core plugin or external pluginifany(core_plugininplugin_rootforcore_pluginin['chat','admin','l8n']):# Core pluginbase_dir=LOCALIZED_FILES_DIR/"coreplugins"else:# External pluginbase_dir=LOCALIZED_FILES_DIR/"external_plugins"# Add .i18n before the file extensionstem=path.stemsuffix=path.suffixnew_filename=f"{stem}.i18n{suffix}"localized_path=base_dir/path.parent/new_filenamereturnlocalized_path
[docs]asyncdefwrite_localized_file(original_path:str,content:str,context=None):"""Write a localized version of a file with static placeholders."""try:localized_path=get_localized_file_path(original_path)# Create directory if it doesn't existlocalized_path.parent.mkdir(parents=True,exist_ok=True)# Write the contentwithopen(localized_path,'w',encoding='utf-8')asf:f.write(content)returnf"Localized file written to: {localized_path}"exceptExceptionase:returnf"Error writing localized file: {str(e)}"
[docs]asyncdefappend_localized_file(original_path:str,content:str,context=None):"""Append content to an existing localized file."""try:localized_path=get_localized_file_path(original_path)# Create directory if it doesn't existlocalized_path.parent.mkdir(parents=True,exist_ok=True)# Append the contentwithopen(localized_path,'a',encoding='utf-8')asf:f.write(content)returnf"Content appended to: {localized_path}"exceptExceptionase:returnf"Error appending to localized file: {str(e)}"
[docs]asyncdefset_translations(language:str,translations:dict,context=None):"""Set translations for a specific language."""try:ifnotisinstance(translations,dict):return"Error: translations must be a dictionary"# Validate translation keysinvalid_keys=[]forkeyintranslations.keys():ifnotre.match(r'^[a-z0-9_]+$',key):invalid_keys.append(key)ifinvalid_keys:returnf"Error: Invalid translation keys: {invalid_keys}"# Store translationsiflanguagenotinTRANSLATIONS:TRANSLATIONS[language]={}TRANSLATIONS[language].update(translations)returnf"Set {len(translations)} translations for language '{language}'. Total languages: {len(TRANSLATIONS)}"exceptExceptionase:returnf"Error setting translations: {str(e)}"
[docs]asyncdefget_translations(language:str=None,context=None):"""Get translations for a specific language or all languages."""try:iflanguage:returnTRANSLATIONS.get(language,{})else:returnTRANSLATIONSexceptExceptionase:returnf"Error getting translations: {str(e)}"
[docs]asyncdeflist_localized_files(context=None):"""List all localized files that have been created."""try:localized_files=[]ifLOCALIZED_FILES_DIR.exists():forfile_pathinLOCALIZED_FILES_DIR.rglob("*.i18n.*"):localized_files.append(str(file_path.relative_to(LOCALIZED_FILES_DIR)))return{"count":len(localized_files),"files":sorted(localized_files)}exceptExceptionase:returnf"Error listing localized files: {str(e)}"
[docs]defreplace_placeholders(content:str,language:str)->str:"""Replace __TRANSLATE_key__ placeholders with actual translations."""iflanguagenotinTRANSLATIONS:returncontenttranslations=TRANSLATIONS[language]defreplace_match(match):key=match.group(1)returntranslations.get(key,match.group(0))# Return original if no translation# Replace all __TRANSLATE_key__ patternsreturnre.sub(r'__TRANSLATE_([a-z0-9_]+)__',replace_match,content)
[docs]asyncdeftest_basic_functionality():"""Test the basic l8n functionality."""print("Testing MindRoot l8n Plugin (Standalone)...\n")# Test 1: Create a localized fileprint("1. Testing write_localized_file...")test_path="/files/mindroot/src/mindroot/coreplugins/chat/templates/chat.jinja2"test_content="<h1>__TRANSLATE_chat_title__</h1><button>__TRANSLATE_buttons_send__</button>"result=awaitwrite_localized_file(test_path,test_content)print(f" Result: {result}")# Test 2: Append to the fileprint("\n2. Testing append_localized_file...")append_content="<p>__TRANSLATE_welcome_message__</p>"result=awaitappend_localized_file(test_path,append_content)print(f" Result: {result}")# Test 3: Set translationsprint("\n3. Testing set_translations...")spanish_translations={'chat_title':'Interfaz de Chat','buttons_send':'Enviar Mensaje','welcome_message':'Bienvenido al chat'}result=awaitset_translations('es',spanish_translations)print(f" Result: {result}")# Test 4: Set more translationsfrench_translations={'chat_title':'Interface de Chat','buttons_send':'Envoyer le Message','welcome_message':'Bienvenue dans le chat'}result=awaitset_translations('fr',french_translations)print(f" Result: {result}")# Test 5: Get translationsprint("\n4. Testing get_translations...")es_translations=awaitget_translations('es')print(f" Spanish translations: {es_translations}")all_translations=awaitget_translations()print(f" All languages: {list(all_translations.keys())}")# Test 6: List localized filesprint("\n5. Testing list_localized_files...")files_result=awaitlist_localized_files()print(f" Result: {files_result}")# Test 7: Test placeholder replacementprint("\n6. Testing placeholder replacement...")test_template="<h1>__TRANSLATE_chat_title__</h1><button>__TRANSLATE_buttons_send__</button><p>__TRANSLATE_welcome_message__</p>"spanish_result=replace_placeholders(test_template,'es')print(f" Spanish: {spanish_result}")french_result=replace_placeholders(test_template,'fr')print(f" French: {french_result}")# Test 8: Test with unknown language (should return original)unknown_result=replace_placeholders(test_template,'de')print(f" German (unknown): {unknown_result}")# Test 9: Check created file contentprint("\n7. Checking created file content...")localized_path=get_localized_file_path(test_path)iflocalized_path.exists():withopen(localized_path,'r',encoding='utf-8')asf:file_content=f.read()print(f" File content: {repr(file_content)}")# Test replacement on actual file contentspanish_file_result=replace_placeholders(file_content,'es')print(f" Spanish version: {spanish_file_result}")else:print(f" File not found: {localized_path}")print("\n✅ All tests completed!")