[TIP] How can I mock pathlib.Path.open and pathlib.path.unlink with the same syntax?
c.buhtz at posteo.jp
c.buhtz at posteo.jp
Sat Jan 29 13:29:06 PST 2022
Hello together,
and sorry for bothering this list with my rookie question. I still asked
that did not received an answer:
https://stackoverflow.com/q/70893660/4865723
I use pathlib.Path.open() and pathlib.Path.unlink() in my productive
code. The unittest for that work. But I use two different ways to
patch(). One with @patch decorator and one with a context manager with
mock.patch().
I would like to use only the @patch decorater like this:
class MyTest(unittest.TestCase):
@mock.patch('pathlib.Path.unlink')
@mock.patch('pathlib.Path.open')
def test_foobar(self, mock_open, mock_unlink):
But I use mock_opener() to input the simulated file content as you can
see in that listing (also visible on StackOverflow). And I do not know
how to use mock_opener() with the @patch decorator.
import unittest
from unittest import mock
import inspect
import pathlib
class MyTest(unittest.TestCase):
@mock.patch('pathlib.Path.unlink')
def test_foobar(self, mock_unlink):
# simulated CSV file
CSV_CONTENT = inspect.cleandoc("""
A;B
1;2
2;1
""")
opener = mock.mock_open(read_data=CSV_CONTENT)
with mock.patch('pathlib.Path.open', opener):
result = validate_csv(file_path=pathlib.Path('foo.csv'))
self.assertTrue(result)
Thanks in advance for reading this.
Kind
Christian
More information about the testing-in-python
mailing list