Repository navigation
Monkeypatching pandas series to_csv with pytest #13087
|
Hello, I am testing a function, Thanks! Tim folder/module.py folder/test_module.py |
Replies: 1 comment 1 reply
|
The file is being created by this line: with open(outpath, "w") as csv_file:not by: pd.Series(entry_names).to_csv(...)Opening a path with mode So even if you successfully patch: pd.Series.to_csvthis still happens: with open(outpath, "w") as csv_file:
# file already exists at this pointIf your goal is to test that For example: mock_to_csv.assert_called_once()can verify the pandas interaction independently. If you want a test with no filesystem interaction at all, mock from unittest.mock import mock_open, patch
def test_write_query(monkeypatch):
mock_to_csv = ...
monkeypatch.setattr(
"your_module.pd.Series.to_csv",
mock_to_csv,
)
with patch("builtins.open", mock_open()):
write_query(df, "output.csv", "name")
mock_to_csv.assert_called_once()If the module imported For this function, though, I would probably use pytest's def test_write_query(tmp_path):
output = tmp_path / "query.csv"
write_query(df, output, "name")
assert output.read_text() == "expected\ncontent\n"That tests the real behavior of So the monkeypatch is not creating the file — Please mark this answer as accepted if it helped, thank you. |
Hi @Tim-Kirkwood
The file is being created by this line:
not by:
Opening a path with mode
"w"creates the file if it doesn't exist (and truncates it if it does).So even if you successfully patch:
this still happens:
If your goal is to test that
to_csv()is called correctly, then the existence of the empty file is expected.For example:
can verify the pandas interaction independently.
If you want a test with no filesystem interaction at all, mock
open()as well: