Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
add tests
mertunsalla3b36b8fb206
diff --git a/tests/ci/test_filesystem.py b/tests/ci/test_filesystem.pyindex 0bc272ec8..a96acf0e0 100644--- a/tests/ci/test_filesystem.py+++ b/tests/ci/test_filesystem.py@@ -1,23 +1,14 @@-"""-Comprehensive tests for the enhanced file system implementation.--Tests cover:-1. File class functionality (MarkdownFile, TxtFile)-2. FileSystem initialization and setup-3. Filename validation and parsing-4. File operations (read, write, append)-5. File access methods (get_file, list_files, display_file)-6. Special methods (describe, save_extracted_content, get_todo_contents)-7. Serialization and deserialization-8. Display functionality with various file sizes-9. Error handling and edge cases-10. Key consistency for same-name different-extension files-"""+"""Tests for the FileSystem class and related file operations."""+import asyncioimport tempfilefrom pathlib import Path+import pytest+from browser_use.filesystem.file_system import (+ DEFAULT_FILE_SYSTEM_PATH,+ INVALID_FILENAME_ERROR_MESSAGE,FileSystem,FileSystemState,MarkdownFile,@@ -25,848 +16,600 @@ from browser_use.filesystem.file_system import ()-class TestFileClasses:- """Test individual file class functionality"""+class TestBaseFile:+ """Test the BaseFile abstract base class and its implementations."""- def test_markdown_file_properties(self):- """Test MarkdownFile basic properties and methods"""- md_file = MarkdownFile(name='test', content='# Header\n\nContent')+ def test_markdown_file_creation(self):+ """Test MarkdownFile creation and basic properties."""+ md_file = MarkdownFile(name='test', content='# Hello World')+ assert md_file.name == 'test'+ assert md_file.content == '# Hello World'assert md_file.extension == 'md'assert md_file.full_name == 'test.md'- assert md_file.validate_content('any string')- assert md_file.read_file_content() == '# Header\n\nContent'- assert md_file.get_line_count() == 3- assert md_file.get_size() == 17-- def test_markdown_file_write_and_append(self):- """Test MarkdownFile write and append methods"""- md_file = MarkdownFile(name='test', content='# Header\n\nContent')-- write_result = md_file.write_file_content('New content')- assert 'successfully' in write_result.lower()- assert md_file.content == 'New content'-- append_result = md_file.append_file_content('\nAppended')- assert 'successfully' in append_result.lower()- assert 'New content\nAppended' in md_file.content+ assert md_file.get_size == 13+ assert md_file.get_line_count == 1- def test_txt_file_properties(self):- """Test TxtFile basic properties and methods"""- txt_file = TxtFile(name='notes', content='Plain text content')+ def test_txt_file_creation(self):+ """Test TxtFile creation and basic properties."""+ txt_file = TxtFile(name='notes', content='Hello\nWorld')+ assert txt_file.name == 'notes'+ assert txt_file.content == 'Hello\nWorld'assert txt_file.extension == 'txt'assert txt_file.full_name == 'notes.txt'- assert txt_file.validate_content('any string')- assert txt_file.read_file_content() == 'Plain text content'-- def test_txt_file_write_and_append(self):- """Test TxtFile write and append methods"""- txt_file = TxtFile(name='notes', content='Initial content')-- write_result = txt_file.write_file_content('New text content')- assert 'successfully' in write_result.lower()- assert txt_file.content == 'New text content'-- append_result = txt_file.append_file_content('\nExtra line')- assert 'successfully' in append_result.lower()- assert 'New text content\nExtra line' in txt_file.content---class TestFileSystemInitialization:- """Test FileSystem initialization and basic setup"""-- def test_filesystem_directory_creation(self):- """Test that FileSystem creates proper directory structure"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Test directory exists- assert fs.get_dir().exists()- assert 'browseruse_agent_data' in str(fs.get_dir())-- def test_default_files_creation(self):- """Test that default files are created during initialization"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Test default files exist- assert 'results.md' in fs.files- assert 'todo.md' in fs.files- assert fs.extracted_content_count == 0-- # Print initial description for verification- initial_description = fs.describe()- print(f'\nπ INITIAL FILE SYSTEM DESCRIPTION:\n{initial_description}')-- def test_filesystem_state_initialization(self):- """Test that FileSystem properly initializes internal state"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- assert isinstance(fs.files, dict)- assert len(fs.files) == 2 # results.md and todo.md- assert fs.extracted_content_count == 0---class TestFilenameValidation:- """Test filename validation and parsing functionality"""-- def test_valid_filename_patterns(self):- """Test that valid filenames are correctly identified"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- valid_files = ['test.md', 'file_name.txt', 'test123.md', 'my-file.txt', 'my_file.md']- for filename in valid_files:- assert fs._is_valid_filename(filename), f'Should accept {filename}'-- def test_invalid_filename_patterns(self):- """Test that invalid filenames are correctly rejected"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- invalid_files = ['test.xyz', 'file.json', 'noextension', 'test.', '.md', 'test..md', 'test space.md']- for filename in invalid_files:- assert not fs._is_valid_filename(filename), f'Should reject {filename}'-- def test_filename_parsing(self):- """Test filename parsing into name and extension"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- name, ext = fs._parse_filename('test.md')- assert name == 'test' and ext == 'md'-- name, ext = fs._parse_filename('complex_file-name.txt')- assert name == 'complex_file-name' and ext == 'txt'-- def test_file_type_class_retrieval(self):- """Test that appropriate file classes are returned for extensions"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- md_class = fs._get_file_type_class('md')- txt_class = fs._get_file_type_class('txt')- unknown_class = fs._get_file_type_class('xyz')-- assert md_class == MarkdownFile- assert txt_class == TxtFile- assert unknown_class == TxtFile # Default fallback---class TestFileOperations:- """Test all file operation methods"""-- async def test_write_file_operations(self):- """Test write_file method with various scenarios"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Test valid file write- write_result = await fs.write_file('test1.md', '# Test Content')- assert 'successfully' in write_result.lower()- assert 'test1.md' in fs.files-- # Test file exists on disk- disk_file = fs.get_dir() / 'test1.md'- assert disk_file.exists()-- # Test invalid filename- invalid_result = await fs.write_file('invalid.xyz', 'content')- assert 'invalid filename format' in invalid_result.lower()-- # Print file system state- operations_description = fs.describe()- print(f'\nπ FILE SYSTEM AFTER WRITE OPERATIONS:\n{operations_description}')-- async def test_read_file_operations(self):- """Test read_file method with various scenarios"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Write a test file first- await fs.write_file('test1.md', '# Test Content')-- # Test reading existing file- read_result = await fs.read_file('test1.md')- assert 'Test Content' in read_result- assert 'Read from file test1.md' in read_result-- # Test reading non-existent file- not_found_result = await fs.read_file('nonexistent.md')- assert 'not found' in not_found_result.lower()-- # Test invalid filename- invalid_read = await fs.read_file('invalid.xyz')- assert 'invalid filename format' in invalid_read.lower()-- async def test_append_file_operations(self):- """Test append_file method with various scenarios"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Write initial file- await fs.write_file('test1.md', '# Test Content')-- # Test appending to existing file- append_result = await fs.append_file('test1.md', '\n\nAppended content')- assert 'successfully' in append_result.lower()-- # Verify append worked- after_append = await fs.read_file('test1.md')- assert 'Appended content' in after_append-- # Test append to non-existent file- append_missing_result = await fs.append_file('missing.md', 'content')- assert 'not found' in append_missing_result.lower()-- # Test invalid filename- invalid_append = await fs.append_file('invalid.xyz', 'content')- assert 'invalid filename format' in invalid_append.lower()---class TestFileAccessMethods:- """Test file access and listing methods"""-- async def test_get_file_method(self):- """Test get_file method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Add test files- await fs.write_file('doc1.md', 'Document 1')- await fs.write_file('doc2.txt', 'Document 2')- await fs.write_file('same_name.md', 'Markdown version')- await fs.write_file('same_name.txt', 'Text version')-- # Test getting existing file- md_file = fs.get_file('doc1.md')- assert md_file is not None- assert md_file.content == 'Document 1'-- # Test getting files with same name but different extension- same_md = fs.get_file('same_name.md')- same_txt = fs.get_file('same_name.txt')- assert same_md is not None and same_txt is not None- assert same_md.content != same_txt.content- assert same_md.content == 'Markdown version'- assert same_txt.content == 'Text version'-- async def test_list_files_method(self):- """Test list_files method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Add test files- await fs.write_file('doc1.md', 'Document 1')- await fs.write_file('doc2.txt', 'Document 2')- await fs.write_file('same_name.md', 'Markdown version')- await fs.write_file('same_name.txt', 'Text version')-- file_list = fs.list_files()- expected_files = {'results.md', 'todo.md', 'doc1.md', 'doc2.txt', 'same_name.md', 'same_name.txt'}- assert set(file_list) == expected_files-- # Print file system state- access_description = fs.describe()- print(f'\nπ FILE SYSTEM WITH MULTIPLE FILES:\n{access_description}')-- async def test_display_file_method(self):- """Test display_file method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- await fs.write_file('doc1.md', 'Document 1')-- # Test displaying existing file- display_content = fs.display_file('doc1.md')- assert display_content == 'Document 1'-- # Test displaying non-existent file- display_none = fs.display_file('nonexistent.md')- assert display_none is None---class TestSpecialMethods:- """Test special methods like describe, save_extracted_content, etc."""-- async def test_describe_method(self):- """Test describe method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Add content to test files- await fs.write_file('results.md', '# Results\n\nSome results here')- await fs.write_file('notes.txt', 'Short note')-- description = fs.describe()-- # Test that files are included/excluded properly- assert 'results.md' in description- assert 'notes.txt' in description- assert 'todo.md' not in description # Should be excluded-- # Test XML formatting- assert '<file>' in description and '</file>' in description- assert '<content>' in description and '</content>' in description-- print(f'\nπ FILE SYSTEM DESCRIPTION TEST:\n{description}')-- async def test_get_todo_contents_method(self):- """Test get_todo_contents method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- await fs.write_file('todo.md', '# TODO\n\n- Task 1\n- Task 2')- todo_contents = fs.get_todo_contents()-- assert 'Task 1' in todo_contents- assert 'Task 2' in todo_contents-- async def test_save_extracted_content_method(self):- """Test save_extracted_content method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- initial_count = fs.extracted_content_count- extract_result = await fs.save_extracted_content('Extracted data')-- assert 'successfully' in extract_result.lower()- assert fs.extracted_content_count == initial_count + 1-- expected_filename = f'extracted_content_{initial_count}.md'- assert expected_filename in fs.files-- # Print file system state- special_description = fs.describe()- print(f'\nπ FILE SYSTEM AFTER SPECIAL METHODS:\n{special_description}')---class TestSerialization:- """Test serialization and deserialization functionality"""-- async def test_get_state_method(self):- """Test get_state method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create filesystem with test data- fs1 = FileSystem(temp_dir)- await fs1.write_file('doc1.md', '# Document 1\n\nContent here')- await fs1.write_file('doc2.txt', 'Plain text document')- await fs1.write_file('same.md', 'Markdown version')- await fs1.write_file('same.txt', 'Text version')- fs1.extracted_content_count = 5-- state = fs1.get_state()-- assert isinstance(state, FileSystemState)- expected_files = {'results.md', 'todo.md', 'doc1.md', 'doc2.txt', 'same.md', 'same.txt'}- assert set(state.files.keys()) == expected_files- assert state.extracted_content_count == 5-- async def test_from_state_method(self):- """Test from_state method functionality"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create original filesystem- fs1 = FileSystem(temp_dir)- await fs1.write_file('doc1.md', '# Document 1\n\nContent here')- await fs1.write_file('doc2.txt', 'Plain text document')- await fs1.write_file('same.md', 'Markdown version')- await fs1.write_file('same.txt', 'Text version')- fs1.extracted_content_count = 5-- # Get state and restore- state = fs1.get_state()- fs2 = FileSystem.from_state(state)-- # Test restoration- assert isinstance(fs2, FileSystem)- expected_files = {'results.md', 'todo.md', 'doc1.md', 'doc2.txt', 'same.md', 'same.txt'}- assert set(fs2.files.keys()) == expected_files- assert fs2.extracted_content_count == 5-- # Test content preservation- doc1_content = await fs2.read_file('doc1.md')- assert 'Document 1' in doc1_content and 'Content here' in doc1_content-- # Test same name different extension preservation- same_md_content = await fs2.read_file('same.md')- same_txt_content = await fs2.read_file('same.txt')- assert 'Markdown version' in same_md_content- assert 'Text version' in same_txt_content-- # Print comparison- original_description = fs1.describe()- restored_description = fs2.describe()- print(f'\nπ ORIGINAL FILE SYSTEM:\n{original_description}')- print(f'\nπ RESTORED FILE SYSTEM:\n{restored_description}')-- async def test_from_state_disk_persistence(self):- """Test that from_state actually writes files to disk"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create original filesystem- fs1 = FileSystem(temp_dir)- await fs1.write_file('test.md', '# Test Content\n\nThis is test content')- await fs1.write_file('data.txt', 'Plain text data')-- # Get state and restore- state = fs1.get_state()- fs2 = FileSystem.from_state(state)-- # Verify files exist on disk in the restored filesystem- test_md_path = fs2.get_dir() / 'test.md'- data_txt_path = fs2.get_dir() / 'data.txt'-- assert test_md_path.exists(), 'test.md should exist on disk after restoration'- assert data_txt_path.exists(), 'data.txt should exist on disk after restoration'-- # Verify content on disk matches- disk_md_content = test_md_path.read_text()- disk_txt_content = data_txt_path.read_text()-- assert '# Test Content' in disk_md_content- assert 'Plain text data' in disk_txt_content-- print('\nπ DISK PERSISTENCE TEST:')- print(f'test.md exists: {test_md_path.exists()}')- print(f'data.txt exists: {data_txt_path.exists()}')- print(f'Disk content matches memory: {disk_md_content == fs2.files["test.md"].content}')-- async def test_from_state_functional_after_restoration(self):- """Test that restored filesystem is fully functional"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create original filesystem- fs1 = FileSystem(temp_dir)- await fs1.write_file('original.md', 'Original content')-- # Get state and restore- state = fs1.get_state()- fs2 = FileSystem.from_state(state)-- # Test all operations work on restored filesystem- # 1. Read existing file- read_result = await fs2.read_file('original.md')- assert 'Original content' in read_result-- # 2. Write new file- write_result = await fs2.write_file('new.txt', 'New content after restoration')- assert 'successfully' in write_result.lower()-- # 3. Append to existing file- append_result = await fs2.append_file('original.md', '\nAppended after restoration')- assert 'successfully' in append_result.lower()-- # 4. List files includes new file- file_list = fs2.list_files()- assert 'new.txt' in file_list-- # 5. Describe works- description = fs2.describe()- assert 'original.md' in description- assert 'new.txt' in description-- print('\nπ FUNCTIONALITY TEST AFTER RESTORATION:')- print(f'Files: {file_list}')- print(f'Description includes new content: {"Appended after restoration" in description}')-- async def test_from_state_with_empty_filesystem(self):- """Test restoration of an empty filesystem"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create filesystem and clear default files- fs1 = FileSystem(temp_dir)- fs1.files.clear() # Remove default files-- # Get state and restore- state = fs1.get_state()- fs2 = FileSystem.from_state(state)-- # Should have no files- assert len(fs2.files) == 0- assert fs2.list_files() == []-- # Should still be functional- write_result = await fs2.write_file('first.md', 'First file in restored empty system')- assert 'successfully' in write_result.lower()- assert len(fs2.files) == 1-- async def test_from_state_extracted_content_counter(self):- """Test that extracted content counter is preserved"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create filesystem and add extracted content- fs1 = FileSystem(temp_dir)- await fs1.save_extracted_content('Content 1')- await fs1.save_extracted_content('Content 2')- await fs1.save_extracted_content('Content 3')-- assert fs1.extracted_content_count == 3-- # Get state and restore- state = fs1.get_state()- fs2 = FileSystem.from_state(state)-- # Counter should be preserved- assert fs2.extracted_content_count == 3-- # Next extracted content should use correct number- await fs2.save_extracted_content('Content 4')- assert fs2.extracted_content_count == 4- assert 'extracted_content_3.md' in fs2.files-- async def test_from_state_with_complex_content(self):- """Test restoration with complex file content"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create filesystem with complex content- fs1 = FileSystem(temp_dir)-- complex_md = """# Complex Markdown File--## Section 1-This is a complex markdown file with:-- Lists-- **Bold text**-- `Code snippets`--### Subsection-More content here.--## Section 2-Final section with special characters: à ÑÒãÀΓ₯ Γ± ΓΌ Γ"""-- complex_txt = """Line 1 with special chars: ~!@#$%^&*()_+-Line 2 with unicode: δ½ ε₯½δΈη-Line 3 with emojis: πππ-Line 4 with quotes: "double" and 'single'-Line 5 with backslashes: \\path\\to\\file"""-- await fs1.write_file('complex.md', complex_md)- await fs1.write_file('complex.txt', complex_txt)+ assert txt_file.get_size == 11+ assert txt_file.get_line_count == 2++ def test_file_content_operations(self):+ """Test content update and append operations."""+ file_obj = TxtFile(name='test')++ # Initial content+ assert file_obj.content == ''+ assert file_obj.get_size == 0++ # Write content+ file_obj.write_file_content('First line')+ assert file_obj.content == 'First line'+ assert file_obj.get_size == 10++ # Append content+ file_obj.append_file_content('\nSecond line')+ assert file_obj.content == 'First line\nSecond line'+ assert file_obj.get_line_count == 2++ # Update content+ file_obj.update_content('New content')+ assert file_obj.content == 'New content'++ async def test_file_disk_operations(self):+ """Test file sync to disk operations."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ tmp_path = Path(tmp_dir)+ file_obj = MarkdownFile(name='test', content='# Test Content')++ # Test sync to disk+ await file_obj.sync_to_disk(tmp_path)++ # Verify file was created on disk+ file_path = tmp_path / 'test.md'+ assert file_path.exists()+ assert file_path.read_text() == '# Test Content'++ # Test write operation+ await file_obj.write('# New Content', tmp_path)+ assert file_path.read_text() == '# New Content'+ assert file_obj.content == '# New Content'++ # Test append operation+ await file_obj.append('\n## Section 2', tmp_path)+ expected_content = '# New Content\n## Section 2'+ assert file_path.read_text() == expected_content+ assert file_obj.content == expected_content++ def test_file_sync_to_disk_sync(self):+ """Test synchronous disk sync operation."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ tmp_path = Path(tmp_dir)+ file_obj = TxtFile(name='sync_test', content='Sync content')++ # Test synchronous sync+ file_obj.sync_to_disk_sync(tmp_path)++ # Verify file was created+ file_path = tmp_path / 'sync_test.txt'+ assert file_path.exists()+ assert file_path.read_text() == 'Sync content'+++class TestFileSystem:+ """Test the FileSystem class functionality."""++ @pytest.fixture+ def temp_filesystem(self):+ """Create a temporary FileSystem for testing."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=True)+ yield fs+ try:+ fs.nuke()+ except Exception:+ pass # Directory might already be cleaned up++ @pytest.fixture+ def empty_filesystem(self):+ """Create a temporary FileSystem without default files."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)+ yield fs+ try:+ fs.nuke()+ except Exception:+ pass++ def test_filesystem_initialization(self, temp_filesystem):+ """Test FileSystem initialization with default files."""+ fs = temp_filesystem++ # Check that base directory and data directory exist+ assert fs.base_dir.exists()+ assert fs.data_dir.exists()+ assert fs.data_dir.name == DEFAULT_FILE_SYSTEM_PATH++ # Check default files are created+ assert 'results.md' in fs.files+ assert 'todo.md' in fs.files+ assert len(fs.files) == 2++ # Check files exist on disk+ results_path = fs.data_dir / 'results.md'+ todo_path = fs.data_dir / 'todo.md'+ assert results_path.exists()+ assert todo_path.exists()++ def test_filesystem_without_default_files(self, empty_filesystem):+ """Test FileSystem initialization without default files."""+ fs = empty_filesystem++ assert fs.base_dir.exists()+ assert fs.data_dir.exists()+ assert len(fs.files) == 0++ def test_get_allowed_extensions(self, temp_filesystem):+ """Test getting allowed file extensions."""+ fs = temp_filesystem+ extensions = fs.get_allowed_extensions()++ assert 'md' in extensions+ assert 'txt' in extensions+ assert len(extensions) == 2++ def test_filename_validation(self, temp_filesystem):+ """Test filename validation."""+ fs = temp_filesystem++ # Valid filenames+ assert fs._is_valid_filename('test.md') is True+ assert fs._is_valid_filename('my_file.txt') is True+ assert fs._is_valid_filename('file-name.md') is True+ assert fs._is_valid_filename('file123.txt') is True++ # Invalid filenames+ assert fs._is_valid_filename('test.doc') is False # wrong extension+ assert fs._is_valid_filename('test') is False # no extension+ assert fs._is_valid_filename('test.md.txt') is False # multiple extensions+ assert fs._is_valid_filename('test with spaces.md') is False # spaces+ assert fs._is_valid_filename('[email protected]') is False # special chars+ assert fs._is_valid_filename('.md') is False # no name++ def test_filename_parsing(self, temp_filesystem):+ """Test filename parsing into name and extension."""+ fs = temp_filesystem++ name, ext = fs._parse_filename('test.md')+ assert name == 'test'+ assert ext == 'md'++ name, ext = fs._parse_filename('my_file.TXT')+ assert name == 'my_file'+ assert ext == 'txt' # Should be lowercased++ def test_get_file(self, temp_filesystem):+ """Test getting files from the filesystem."""+ fs = temp_filesystem++ # Get existing file+ results_file = fs.get_file('results.md')+ assert results_file is not None+ assert isinstance(results_file, MarkdownFile)+ assert results_file.name == 'results'++ # Get non-existent file+ non_existent = fs.get_file('nonexistent.md')+ assert non_existent is None++ # Get file with invalid name+ invalid = fs.get_file('[email protected]')+ assert invalid is None++ def test_list_files(self, temp_filesystem):+ """Test listing files in the filesystem."""+ fs = temp_filesystem+ files = fs.list_files()++ assert 'results.md' in files+ assert 'todo.md' in files+ assert len(files) == 2++ def test_display_file(self, temp_filesystem):+ """Test displaying file content."""+ fs = temp_filesystem++ # Display existing file+ content = fs.display_file('results.md')+ assert content == '' # Default files are empty++ # Display non-existent file+ content = fs.display_file('nonexistent.md')+ assert content is None++ # Display file with invalid name+ content = fs.display_file('[email protected]')+ assert content is None++ def test_read_file(self, temp_filesystem):+ """Test reading file content with proper formatting."""+ fs = temp_filesystem++ # Read existing empty file+ result = fs.read_file('results.md')+ expected = 'Read from file results.md.\n<content>\n\n</content>'+ assert result == expected++ # Read non-existent file+ result = fs.read_file('nonexistent.md')+ assert result == "File 'nonexistent.md' not found."++ # Read file with invalid name+ result = fs.read_file('[email protected]')+ assert result == INVALID_FILENAME_ERROR_MESSAGE++ async def test_write_file(self, temp_filesystem):+ """Test writing content to files."""+ fs = temp_filesystem++ # Write to existing file+ result = await fs.write_file('results.md', '# Test Results\nThis is a test.')+ assert result == 'Data written to file results.md successfully.'++ # Verify content was written+ content = fs.read_file('results.md')+ assert '# Test Results\nThis is a test.' in content++ # Write to new file+ result = await fs.write_file('new_file.txt', 'New file content')+ assert result == 'Data written to file new_file.txt successfully.'+ assert 'new_file.txt' in fs.files+ assert fs.get_file('new_file.txt').content == 'New file content'++ # Write with invalid filename+ result = await fs.write_file('[email protected]', 'content')+ assert result == INVALID_FILENAME_ERROR_MESSAGE++ # Write with invalid extension+ result = await fs.write_file('test.doc', 'content')+ assert result == INVALID_FILENAME_ERROR_MESSAGE++ async def test_append_file(self, temp_filesystem):+ """Test appending content to files."""+ fs = temp_filesystem++ # First write some content+ await fs.write_file('test.md', '# Title')++ # Append content+ result = await fs.append_file('test.md', '\n## Section 1')+ assert result == 'Data appended to file test.md successfully.'++ # Verify content was appended+ content = fs.get_file('test.md').content+ assert content == '# Title\n## Section 1'++ # Append to non-existent file+ result = await fs.append_file('nonexistent.md', 'content')+ assert result == "File 'nonexistent.md' not found."++ # Append with invalid filename+ result = await fs.append_file('[email protected]', 'content')+ assert result == INVALID_FILENAME_ERROR_MESSAGE++ async def test_save_extracted_content(self, temp_filesystem):+ """Test saving extracted content with auto-numbering."""+ fs = temp_filesystem++ # Save first extracted content+ result = await fs.save_extracted_content('First extracted content')+ assert result == 'Extracted content saved to file extracted_content_0.md successfully.'+ assert 'extracted_content_0.md' in fs.files+ assert fs.extracted_content_count == 1++ # Save second extracted content+ result = await fs.save_extracted_content('Second extracted content')+ assert result == 'Extracted content saved to file extracted_content_1.md successfully.'+ assert 'extracted_content_1.md' in fs.files+ assert fs.extracted_content_count == 2++ # Verify content+ content1 = fs.get_file('extracted_content_0.md').content+ content2 = fs.get_file('extracted_content_1.md').content+ assert content1 == 'First extracted content'+ assert content2 == 'Second extracted content'++ async def test_describe_empty_files(self, temp_filesystem):+ """Test describing filesystem with empty files."""+ fs = temp_filesystem++ description = fs.describe()++ # Should contain results.md but not todo.md (excluded from description)+ assert 'results.md' in description+ assert 'todo.md' not in description+ assert '[empty file]' in description++ async def test_describe_with_content(self, temp_filesystem):+ """Test describing filesystem with files containing content."""+ fs = temp_filesystem++ # Add content to files+ await fs.write_file('results.md', '# Results\nTest results here.')+ await fs.write_file('notes.txt', 'These are my notes.')++ description = fs.describe()++ # Should contain file information+ assert 'results.md' in description+ assert 'notes.txt' in description+ assert '# Results' in description+ assert 'These are my notes.' in description+ assert 'lines' in description++ async def test_describe_large_files(self, temp_filesystem):+ """Test describing filesystem with large files (truncated content)."""+ fs = temp_filesystem++ # Create a large file+ large_content = '\n'.join([f'Line {i}' for i in range(100)])+ await fs.write_file('large.md', large_content)++ description = fs.describe()++ # Should be truncated with "more lines" indicator+ assert 'large.md' in description+ assert 'more lines' in description+ assert 'Line 0' in description # Start should be shown+ assert 'Line 99' in description # End should be shown++ def test_get_todo_contents(self, temp_filesystem):+ """Test getting todo file contents."""+ fs = temp_filesystem++ # Initially empty+ todo_content = fs.get_todo_contents()+ assert todo_content == ''++ # Add content to todo+ fs.get_file('todo.md').update_content('- [ ] Task 1\n- [ ] Task 2')+ todo_content = fs.get_todo_contents()+ assert '- [ ] Task 1' in todo_content++ def test_get_state(self, temp_filesystem):+ """Test getting filesystem state."""+ fs = temp_filesystem++ state = fs.get_state()++ assert isinstance(state, FileSystemState)+ assert state.base_dir == str(fs.base_dir)+ assert state.extracted_content_count == 0+ assert 'results.md' in state.files+ assert 'todo.md' in state.files++ # Check file data structure+ results_data = state.files['results.md']+ assert results_data['type'] == 'MarkdownFile'+ assert 'data' in results_data+ assert results_data['data']['name'] == 'results'++ async def test_from_state(self, temp_filesystem):+ """Test restoring filesystem from state."""+ fs = temp_filesystem++ # Add some content+ await fs.write_file('results.md', '# Original Results')+ await fs.write_file('custom.txt', 'Custom content')+ await fs.save_extracted_content('Extracted data')++ # Get state+ state = fs.get_state()++ # Create new filesystem from state+ fs2 = FileSystem.from_state(state)++ # Verify restoration+ assert fs2.base_dir == fs.base_dir+ assert fs2.extracted_content_count == fs.extracted_content_count+ assert len(fs2.files) == len(fs.files)++ # Verify file contents+ assert fs2.get_file('results.md').content == '# Original Results'+ assert fs2.get_file('custom.txt').content == 'Custom content'+ assert fs2.get_file('extracted_content_0.md').content == 'Extracted data'++ # Verify files exist on disk+ assert (fs2.data_dir / 'results.md').exists()+ assert (fs2.data_dir / 'custom.txt').exists()+ assert (fs2.data_dir / 'extracted_content_0.md').exists()++ # Clean up second filesystem+ fs2.nuke()++ def test_nuke(self, empty_filesystem):+ """Test filesystem destruction."""+ fs = empty_filesystem++ # Create a file to ensure directory has content+ fs.data_dir.mkdir(exist_ok=True)+ test_file = fs.data_dir / 'test.txt'+ test_file.write_text('test')+ assert test_file.exists()++ # Nuke the filesystem+ fs.nuke()++ # Verify directory is removed+ assert not fs.data_dir.exists()++ def test_get_dir(self, temp_filesystem):+ """Test getting the filesystem directory."""+ fs = temp_filesystem++ directory = fs.get_dir()+ assert directory == fs.data_dir+ assert directory.exists()+ assert directory.name == DEFAULT_FILE_SYSTEM_PATH+++class TestFileSystemEdgeCases:+ """Test edge cases and error handling."""++ def test_filesystem_with_string_path(self):+ """Test FileSystem creation with string path."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)+ assert isinstance(fs.base_dir, Path)+ assert fs.base_dir.exists()+ fs.nuke()++ def test_filesystem_with_path_object(self):+ """Test FileSystem creation with Path object."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ path_obj = Path(tmp_dir)+ fs = FileSystem(base_dir=path_obj, create_default_files=False)+ assert isinstance(fs.base_dir, Path)+ assert fs.base_dir == path_obj+ fs.nuke()++ def test_filesystem_recreates_data_dir(self):+ """Test that FileSystem recreates data directory if it exists."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ # Create filesystem+ fs1 = FileSystem(base_dir=tmp_dir, create_default_files=True)+ data_dir = fs1.data_dir++ # Add a custom file+ custom_file = data_dir / 'custom.txt'+ custom_file.write_text('custom content')+ assert custom_file.exists()++ # Create another filesystem with same base_dir (should clean data_dir)+ fs2 = FileSystem(base_dir=tmp_dir, create_default_files=True)++ # Custom file should be gone, default files should exist+ assert not custom_file.exists()+ assert (fs2.data_dir / 'results.md').exists()+ assert (fs2.data_dir / 'todo.md').exists()++ fs2.nuke()++ async def test_write_file_exception_handling(self):+ """Test exception handling in write_file."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ # Test with invalid extension+ result = await fs.write_file('test.invalid', 'content')+ assert result == INVALID_FILENAME_ERROR_MESSAGE++ fs.nuke()++ def test_from_state_with_unknown_file_type(self):+ """Test restoring state with unknown file types (should skip them)."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ # Create a state with unknown file type+ state = FileSystemState(+ files={+ 'test.md': {'type': 'MarkdownFile', 'data': {'name': 'test', 'content': 'test content'}},+ 'unknown.txt': {'type': 'UnknownFileType', 'data': {'name': 'unknown', 'content': 'unknown content'}},+ },+ base_dir=tmp_dir,+ extracted_content_count=0,+ )++ # Restore from state+ fs = FileSystem.from_state(state)++ # Should only have the known file type+ assert 'test.md' in fs.files+ assert 'unknown.txt' not in fs.files+ assert len(fs.files) == 1++ fs.nuke()+++class TestFileSystemIntegration:+ """Integration tests for FileSystem with real file operations."""++ async def test_complete_workflow(self):+ """Test a complete filesystem workflow."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ # Create filesystem+ fs = FileSystem(base_dir=tmp_dir, create_default_files=True)++ # Write to results file+ await fs.write_file('results.md', '# Test Results\n## Section 1\nInitial results.')++ # Append more content+ await fs.append_file('results.md', '\n## Section 2\nAdditional findings.')++ # Create a notes file+ await fs.write_file('notes.txt', 'Important notes:\n- Note 1\n- Note 2')++ # Save extracted content+ await fs.save_extracted_content('Extracted data from web page')+ await fs.save_extracted_content('Second extraction')++ # Verify file listing+ files = fs.list_files()+ assert len(files) == 5 # results.md, todo.md, notes.txt, 2 extracted files++ # Verify content+ results_content = fs.get_file('results.md').content+ assert '# Test Results' in results_content+ assert '## Section 1' in results_content+ assert '## Section 2' in results_content+ assert 'Additional findings.' in results_content++ # Test state persistence+ state = fs.get_state()+ fs.nuke()- # Get state and restore- state = fs1.get_state()+ # Restore from statefs2 = FileSystem.from_state(state)- # Verify complex content is preserved- restored_md = await fs2.read_file('complex.md')- restored_txt = await fs2.read_file('complex.txt')-- assert 'Complex Markdown File' in restored_md- assert 'δ½ ε₯½δΈη' in restored_txt- assert 'πππ' in restored_txt- assert '\\path\\to\\file' in restored_txt-- print('\nπ COMPLEX CONTENT TEST:')- print(f'Special characters preserved: {"à ÑÒãÀΓ₯" in restored_md}')- print(f'Unicode preserved: {"δ½ ε₯½δΈη" in restored_txt}')- print(f'Emojis preserved: {"πππ" in restored_txt}')-- async def test_from_state_directory_structure(self):- """Test that from_state creates proper directory structure"""- with tempfile.TemporaryDirectory() as temp_dir:- # Create original filesystem- fs1 = FileSystem(temp_dir)- await fs1.write_file('test.md', 'content')-- # Get state- state = fs1.get_state()-- # Verify state has correct path- assert 'browseruse_agent_data' in state.base_dir-- # Restore to different location- with tempfile.TemporaryDirectory() as new_temp_dir:- # Modify state to point to new location- new_state = FileSystemState(- files=state.files,- base_dir=str(Path(new_temp_dir) / 'browseruse_agent_data'),- extracted_content_count=state.extracted_content_count,- )-- fs2 = FileSystem.from_state(new_state)-- # Verify directory structure- assert fs2.get_dir().exists()- assert 'browseruse_agent_data' in str(fs2.get_dir())- assert fs2.get_dir() != fs1.get_dir() # Different locations-- # Verify file exists in new location- test_file_path = fs2.get_dir() / 'test.md'- assert test_file_path.exists()-- print('\nπ DIRECTORY STRUCTURE TEST:')- print(f'Original dir: {fs1.get_dir()}')- print(f'Restored dir: {fs2.get_dir()}')- print(f'File exists in new location: {test_file_path.exists()}')-- def test_from_state_error_handling(self):- """Test error handling in from_state method"""- # Test with invalid file type in state- invalid_state = FileSystemState(- files={'invalid.md': {'type': 'NonExistentFileType', 'data': {'name': 'invalid', 'content': 'test'}}},- base_dir='/tmp/test_invalid',- extracted_content_count=0,- )-- # Should fallback to TxtFile for unknown types- fs = FileSystem.from_state(invalid_state)- assert 'invalid.md' in fs.files- assert isinstance(fs.files['invalid.md'], TxtFile) # Should fallback to TxtFile-- print('\nπ ERROR HANDLING TEST:')- print(f'Unknown file type handled gracefully: {type(fs.files["invalid.md"]).__name__}')---class TestDisplayFunctionality:- """Test file system display functionality with various file sizes and content"""-- async def test_empty_file_display(self):- """Test display of empty files"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- await fs.write_file('empty.md', '')- description = fs.describe()-- assert '[empty file]' in description- print(f'\nπ EMPTY FILE DISPLAY:\n{description}')-- async def test_small_file_display(self):- """Test display of small files (should show complete content)"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- small_content = '# Small File\n\nThis is a small file with just a few lines.\nLine 3\nLine 4'- await fs.write_file('small.md', small_content)- description = fs.describe()-- assert 'Small File' in description and 'Line 4' in description- print(f'\nπ SMALL FILE DISPLAY:\n{description}')-- async def test_medium_file_display(self):- """Test display of medium files (around threshold)"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Create content around threshold- medium_lines = [f'This is line {i + 1} with some content to make it longer' for i in range(20)]- medium_content = '\n'.join(medium_lines)- await fs.write_file('medium.txt', medium_content)-- description = fs.describe()- assert 'line 1' in description and 'line 20' in description- print(f'\nπ MEDIUM FILE DISPLAY:\n{description[:500]}...')-- async def test_large_file_display(self):- """Test display of large files (should show truncation)"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Create large content that will be truncated- large_lines = []- for i in range(100):- large_lines.append(- f'This is a very long line {i + 1} with lots of content to exceed the display character limit and force truncation behavior in the describe method'- )- large_content = '\n'.join(large_lines)- await fs.write_file('large.md', large_content)-- description = fs.describe()- assert 'line 1' in description and 'line 100' in description- assert 'more lines' in description- print(f'\nπ LARGE FILE DISPLAY (truncated):\n{description[:800]}...')-- async def test_threshold_file_display(self):- """Test display of files at exact threshold"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Create content at threshold (590 chars)- threshold_content = 'x' * 590- await fs.write_file('threshold.txt', threshold_content)- description = fs.describe()-- assert threshold_content[:50] in description- print(f'\nπ THRESHOLD FILE DISPLAY:\n{description}')-- async def test_line_count_accuracy(self):- """Test that line counts are displayed accurately"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- test_content = 'Line 1\nLine 2\nLine 3\nLine 4\nLine 5'- await fs.write_file('linecount.md', test_content)- description = fs.describe()-- assert '5 lines' in description-- async def test_xml_formatting(self):- """Test that XML formatting is correct"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- await fs.write_file('test.md', 'Test content')- description = fs.describe()-- # Test balanced XML tags- assert description.count('<file>') == description.count('</file>')- assert '<content>' in description and '</content>' in description-- async def test_comprehensive_display_output(self):- """Test comprehensive display with all file types and sizes"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Create various types of files- await fs.write_file('empty.md', '')- await fs.write_file('small.txt', 'Short content')-- # Medium file- medium_lines = [f'Line {i + 1} content' for i in range(15)]- await fs.write_file('medium.md', '\n'.join(medium_lines))-- # Large file- large_lines = [f'Very long line {i + 1} with extensive content for testing truncation behavior' for i in range(50)]- await fs.write_file('large.txt', '\n'.join(large_lines))-- # Mixed file types- await fs.write_file('mixed1.md', '# Markdown file\n\nWith some content')- await fs.write_file('mixed2.txt', 'Plain text file\nWith some content')-- sample_description = fs.describe()+ # Verify restoration+ assert len(fs2.files) == 5+ assert fs2.get_file('results.md').content == results_content+ assert fs2.get_file('notes.txt').content == 'Important notes:\n- Note 1\n- Note 2'+ assert fs2.extracted_content_count == 2- print('\nπ COMPREHENSIVE DISPLAY OUTPUT:')- print('=' * 60)- print(sample_description)- print('=' * 60)- print('\nDescription Statistics:')- print(f'- Total length: {len(sample_description)} characters')- print(f'- Total files in system: {len(fs.files)}')- print(f'- Files shown in description: {sample_description.count("<file>")}')- print(f'- Files with truncation: {sample_description.count("more lines")}')+ # Verify files exist on disk+ for filename in files:+ assert (fs2.data_dir / filename).exists()- # Basic assertions- assert len(sample_description) > 0- assert sample_description.count('<file>') > 0+ fs2.nuke()+ async def test_concurrent_operations(self):+ """Test concurrent file operations."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)-class TestErrorHandling:- """Test error handling and edge cases"""-- async def test_invalid_filename_error_handling(self):- """Test error handling for invalid filenames"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Test various invalid filename operations- invalid_read = await fs.read_file('invalid.xyz')- assert 'invalid filename format' in invalid_read.lower()-- invalid_write = await fs.write_file('invalid.xyz', 'content')- assert 'invalid filename format' in invalid_write.lower()-- invalid_append = await fs.append_file('invalid.xyz', 'content')- assert 'invalid filename format' in invalid_append.lower()-- async def test_nonexistent_file_error_handling(self):- """Test error handling for non-existent files"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- read_missing = await fs.read_file('missing.md')- assert 'not found' in read_missing.lower()-- append_missing = await fs.append_file('missing.md', 'content')- assert 'not found' in append_missing.lower()-- def test_get_file_with_invalid_filename(self):- """Test get_file with invalid filename returns None"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- result = fs.get_file('invalid.xyz')- assert result is None-- def test_display_file_with_nonexistent_file(self):- """Test display_file with non-existent file returns None"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- result = fs.display_file('nonexistent.md')- assert result is None---class TestKeyConsistency:- """Test that all dictionary keys consistently use full filenames"""-- async def test_full_filename_keys(self):- """Test that all dictionary keys use full filenames with extensions"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- # Add files with same names but different extensions- await fs.write_file('test.md', 'Markdown content')- await fs.write_file('test.txt', 'Text content')- await fs.write_file('document.md', 'Another markdown')- await fs.write_file('document.txt', 'Another text')-- all_keys = list(fs.files.keys())-- # Test all keys have extensions- assert all('.' in key for key in all_keys)-- # Test no duplicate keys- assert len(all_keys) == len(set(all_keys))-- async def test_same_name_different_extension_access(self):- """Test accessing files with same names but different extensions"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- await fs.write_file('test.md', 'Markdown content')- await fs.write_file('test.txt', 'Text content')-- # Test both files are accessible- test_md = await fs.read_file('test.md')- test_txt = await fs.read_file('test.txt')-- assert 'Markdown content' in test_md- assert 'Text content' in test_txt-- async def test_serialization_key_preservation(self):- """Test that serialization preserves full filename keys"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)-- await fs.write_file('test.md', 'Markdown content')- await fs.write_file('test.txt', 'Text content')- await fs.write_file('document.md', 'Another markdown')- await fs.write_file('document.txt', 'Another text')-- all_keys = list(fs.files.keys())-- # Test serialization preserves keys- state = fs.get_state()- state_keys = list(state.files.keys())- assert set(state_keys) == set(all_keys)-- # Test deserialization preserves keys- fs2 = FileSystem.from_state(state)- restored_keys = list(fs2.files.keys())- assert set(restored_keys) == set(all_keys)-- # Print verification- consistency_description = fs.describe()- print(f'\nπ SAME-NAME DIFFERENT-EXTENSION FILES:\n{consistency_description}')+ # Create multiple files concurrently+ tasks = []+ for i in range(5):+ tasks.append(fs.write_file(f'file_{i}.md', f'Content for file {i}'))+ # Wait for all operations to complete+ results = await asyncio.gather(*tasks)-class TestFileSystemDirectory:- """Test directory-related functionality"""+ # Verify all operations succeeded+ for result in results:+ assert 'successfully' in result- def test_get_dir_method(self):- """Test get_dir method returns correct directory"""- with tempfile.TemporaryDirectory() as temp_dir:- fs = FileSystem(temp_dir)+ # Verify all files were created+ assert len(fs.files) == 5+ for i in range(5):+ assert f'file_{i}.md' in fs.files+ assert fs.get_file(f'file_{i}.md').content == f'Content for file {i}'- dir_path = fs.get_dir()- assert isinstance(dir_path, Path)- assert dir_path.exists()- assert 'browseruse_agent_data' in str(dir_path)+ fs.nuke()