import pytest import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from functions.io_utils import * import warnings import io from unittest import mock def test_write_file(tmp_path): # Write content to file and verify write success file = tmp_path / "test_write.txt" write_file(str(file), "data") assert file.read_text() == "data" def test_read_file(tmp_path): # Write and read file, normal operation file = tmp_path / "test.txt" file.write_text("hello") content = read_file(str(file)) assert content == "hello" def test_cause_io_error(): # Raises manual IOError to simulate IO failure cause_io_error() def test_file_not_found(): # Reading non-existing file raises FileNotFoundError read_file("nonexistent.file") def test_permission_error(monkeypatch): # Patch open to raise PermissionError simulating access denial def raise_perm_error(*args, **kwargs): raise PermissionError("Permission denied") monkeypatch.setattr("builtins.open", raise_perm_error) read_file("anyfile.txt") def test_mock_open_error(monkeypatch): # Mock open() to raise IOError simulating read error mocked_open = mock.mock_open() mocked_open.side_effect = IOError("Mocked IOError") monkeypatch.setattr("builtins.open", mocked_open) with open("file.txt", "r") as f: f.read() def test_file_handle_closed_error(): # Accessing closed file raises ValueError f = io.StringIO("content") f.close() f.read() def test_os_error(monkeypatch): # Patch os.remove to raise OSError simulating filesystem error def raise_os_error(path): raise OSError("Simulated OSError") monkeypatch.setattr("os.remove", raise_os_error) os.remove("file.txt") def test_write_file_in_readonly_mode(tmp_path): # Writing to read-only file raises PermissionError file = tmp_path / "readonly.txt" file.write_text("data") # Change the file's permissions to read-only : no write permission os.chmod(file, 0o444) with open(file, "w") as f: f.write("new content") def test_file_not_found_error(): # Raises FileNotFoundError when opening a non-existent file open("no_such_file.txt", "r")