Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I use fixture to create a mock file of certain size?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading