How to mock aiofiles.open?

198 Views Asked by At

I'm trying to mock aiofiles.open and failing.

This is my code: ds_feature_store/main.py

async def read_json(path):
    async with aiofiles.open(path, "r") as f:
        return (
            path.removeprefix(f"{SCHEMAS_PATH}/").removesuffix(".json"),
            json.loads(await f.read()),
    )

async def startup_engine():
for feature_group, schema in await asyncio.gather(
    *[
        read_json(os.path.join(SCHEMAS_PATH, file))
        for file in os.listdir(SCHEMAS_PATH)
        if file.endswith(".json")
    ]
):
    feature_store_schemas[feature_group] = schema

This is how I'm trying to patch these functions calls.

with patch("ds_feature_store_api.main.os.listdir") as os_listdir:
    os_listdir.return_value = ["events_main.json", "events_extra.json"]
    with patch("ds_feature_store_api.main.aiofiles.open") as aiofiles_open:
        aiofiles_open.return_value.__aenter__.return_value.read = AsyncMock(return_value=b'{"record_identifier": "id"}')

The patch to os.listdir works, but the patch to aiofiles.open doesn't do anything.

0

There are 0 best solutions below