I’m doing something like this
def test_collection_size(create_fake_file):
files = [create_fake_file]
size = get_collection_size(files)
assert size == 32
create_fake_file fixture should return a mock file of size 32 bytes
I did something like this
@pytest.fixture
def fake_file_content():
# Returns 32 bytes of space
return b" " * 32
@pytest.fixture
def create_fake_file(fake_file_content):
def _create_fake_file(file_path):
# Use unittest.mock.mock_open to create a mock file object
mock_file = Mock(spec=open, read=Mock(return_value=fake_file_content))
# Use unittest.mock.patch to replace the built-in open function with the mock_file
with pytest.patch("builtins.open", mock_open(read_data=mock_file.read)):
# Write the fake content to the specified file path
with open(file_path, "wb") as file:
file.write(fake_file_content)
return _create_fake_file
- I’m getting
TypeError: stat: path should be string, bytes, os.PathLike or integer, not function
>Solution :
First, I would recommend not mocking. Why do you need to mock out the file system?
Pytest has the feature to create mock directories & files for testing.
Do something like this
@pytest.fixture(scope="session")
def create_fake_file(tmp_path_factory):
# Create a temporary file in the tmp_path directory
temp_file = tmp_path_factory.mktemp("temp") / "temp_file.txt"
# Write 32 bytes of data to the file
temp_file.write_bytes(b"a" * 32)
return temp_file
# test
def test_collection_size(create_fake_file):
files = [create_fake_file]
size = get_collection_size(files)
assert size == 32