Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocked patch of os.listdir not working for unittesting

I have a class method that I am trying to test that requires two patched methods, ConfigB.__init__ and listdir:

from os import listdir
from config.ConfigB import ConfigB

class FileRunner(object):
  def runProcess(self, cfgA)
    cfgB = ConfigB(cfgA)
    print(listdir())

I have the following test set up:

import unittest
import unittest.mock imort MagicMock
import mock
from FileRunner import FileRunner

class TestFileRunner(unittest.TestCase):
  @mock.patch('ConfigB.ConfigB.__init__')
  @mock.patch('os.listdir')
  def test_methodscalled(self, osListDir, cfgB):
    
    cfgA = MagicMock()
    fileRunner = FileRunner()

    cfgB.return_value = None
    osListDir.return_value = None

    fileRunner.runProcess(cfgA)

Now the patched mock and return value works for ConfigB.ConfigB, but it does not work for os.listdir. When the print(listdir()) method runs I get a list of file in the current directory, not a value of None as I specified in the patched return value. Any idea what is going wrong?

like image 260
EliSquared Avatar asked Jun 15 '17 16:06

EliSquared


1 Answers

You need to patch your relative path to your code. patch('os.listdir') doesn't works because you need to patch this:

@mock.patch("path.to.your.pythonfile.listdir")

Try with that.

like image 98
Juan Diego Garcia Avatar answered Oct 24 '22 21:10

Juan Diego Garcia