0

How to write tests to a function using the newly added to build-ins of python 3.5 os.scandir()? Is there a helper to mock a DirEntry objects?

Any suggestions on how to mock os.scandir() of an empty folder and a folder with few 2 files for example?

vmenezes
  • 1,076
  • 2
  • 12
  • 21
  • I think you are looking for [mock.patch()](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch) decorator – Compadre Aug 15 '16 at 19:11

1 Answers1

2

As suggested, my solution involves @mock.patch() decorator. My test became something like:

from django.test import TestCase, mock
from my_app.scan_files import my_method_that_return_count_of_files

mock_one_file = mock.MagicMock(return_value = ['one_file', ])

class MyMethodThatReturnCountOfFilesfilesTestCase(TestCase):
    @mock.patch('os.scandir', mock_one_file)
    def test_get_one(self):
        """ Test it receives 1 (one) file """
        files_count = my_method_that_return_count_of_files('/anything/')
        self.assertEqual(files_count, 1)
vmenezes
  • 1,076
  • 2
  • 12
  • 21