mocking a variable using mox

1.4k views Asked by At

I want to test this method, however I would need to mock the variable dirContent

def imageFilePaths(paths):
    imagesWithPath = []
    for _path in paths:
        try:
            dirContent = os.listdir(_path)
        except OSError:
            raise OSError("Provided path '%s' doesn't exists." % _path)

        for each in dirContent:
            selFile = os.path.join(_path, each)
            if os.path.isfile(selFile) and isExtensionSupported(selFile):
                imagesWithPath.append(selFile)
    return list(set(imagesWithPath))

how do I just mock a variable using mox ? This is how I have however tried to mock os.listdir

def setUp(self):
    self._filePaths = ["/test/file/path"]
    self.mox = mox.Mox()

def test_imageFilePaths(self):
    filePaths = self._filePaths[0]
    self.mox.StubOutWithMock(os,'listdir')
    dirContent = os.listdir(filePaths).AndReturn(['file1.jpg','file2.PNG','file3.png'])

    self.mox.ReplayAll()

    utils.imageFilePaths(filePaths)
    self.mox.VerifyAll()

also tried this way

def test_imageFilePaths(self):
    filePaths = self._filePaths
    os = self.mox.CreateMock('os')
    os.listdir = self.mox.CreateMock(os)
    dirContent = os.listdir(filePaths).AndReturn(['file1.jpg','file2.PNG','file3.png'])
    self.mox.ReplayAll()
    lst = utils.imageFilePaths(filePaths)
    # self.assertEquals('/test/file/path/file1.jpg', lst[0])
    self.mox.VerifyAll()

but the call to method being tested doesn't recognizes the mocked discontent

1

There are 1 answers

2
Amber On BEST ANSWER

Typically you would not mock a variable, but instead mock the function call used to set that variable's value. In your example, for instance, you'd mock out os.listdir and have it return a mock value.

# Your test file
import os

class YourTest(...):

    def setUp(self):
        self.mox = mox.Mox()


    def tearDown(self):
        self.mox.UnsetStubs()

    # Your test
    def testFoo(self):
        self.mox.StubOutWithMock(os, 'listdir')

        # the calls you expect to listdir, and what they should return
        os.listdir("some path").AndReturn([...])

        self.mox.ReplayAll()
        # ... the rest of your test