I have my own repository format, and I'm trying to develop a Python module to handle these repositories. Repo format:
/home/X/ | + alpha/ | + beta/ | + project.conf
Here X is the project. alpha and beta are folders within this project, and they represent groups in this project. The group is a container in this repo, and what it represents is really irrelevant to this issue. Repo X also has files at its root level; project.conf is an example of such a file.
I have a class called Project that abstracts projects like X The Project class has a load() method that creates a view in memory.
class Project(object): def load(self): for entry in os.listdir(self.root): path = os.path.join(self.root, entry) if os.path.isdir(path): group = Group(path) self.groups.append(group) group.load() else:
In the unit test, the load() method, making fun of the file system, I:
import unittest from unittest import mock import Project class TestRepo(unittest.TestCase): def test_load_project(self): project = Project("X") with mock.patch('os.listdir') as mocked_listdir: mocked_listdir.return_value = ['alpha', 'beta', 'project.conf'] project.load() self.assertEqual(len(project.groups), 2)
This makes mock os.listdir successful. But I canβt trick Python into treating mocked_listdir.return_value as consisting of files and directories.
How do I mock os.listdir or os.path.isdir in the same test that the test will display alpha and beta as directories and project.conf as a file
python unit-testing mocking
Upendra
source share