vmenezes
vmenezes

Reputation: 1246

how to write tests for a function using py3.5 os.scandir()?

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?

Upvotes: 0

Views: 762

Answers (1)

vmenezes
vmenezes

Reputation: 1246

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)

Upvotes: 2

Related Questions