Skip to content

Commit

Permalink
[README] Update readme for testing read() in aiofiles' stream (#179)
Browse files Browse the repository at this point in the history
* Update README.md for mocking read file

* Update README.md

* Update README.md

* Update README.md
  • Loading branch information
jiachin1995 committed Feb 6, 2024
1 parent 213ee8b commit e2bcd7f
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,17 +150,29 @@ as desired. The return type also needs to be registered with the

```python
aiofiles.threadpool.wrap.register(mock.MagicMock)(
lambda *args, **kwargs: threadpool.AsyncBufferedIOBase(*args, **kwargs))
lambda *args, **kwargs: aiofiles.threadpool.AsyncBufferedIOBase(*args, **kwargs)
)

async def test_stuff():
data = 'data'
mock_file = mock.MagicMock()

with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file) as mock_open:
write_data = 'data'
read_file_chunks = [
b'file chunks 1',
b'file chunks 2',
b'file chunks 3',
b'',
]
file_chunks_iter = iter(read_file_chunks)

mock_file_stream = mock.MagicMock(
read=lambda *args, **kwargs: next(file_chunks_iter)
)

with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file_stream) as mock_open:
async with aiofiles.open('filename', 'w') as f:
await f.write(data)
await f.write(write_data)
assert f.read() == b'file chunks 1'

mock_file.write.assert_called_once_with(data)
mock_file_stream.write.assert_called_once_with(write_data)
```

### History
Expand Down

0 comments on commit e2bcd7f

Please sign in to comment.