0

I'm trying to mock os.path.curdir so it returns given return_value but this does not work.

from os.path import curdir
from unittest import TestCase
from unittest.mock import patch

from hello import Hello


class Hello:
    def hey(self):
        return curdir


class TestHello(TestCase):
    @patch('os.path.curdir')
    def test_hey(self, mock):
        mock.return_value = 'mock'
        h = Hello()
        res = h.hey()

        assert res == 'mock'

What am I missing?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Meroz
  • 859
  • 2
  • 8
  • 28

1 Answers1

1

You should patch the curdir variable for hello.py module. So the patched target should be hello.curdir. For more info, see where-to-patch.

E.g.

hello.py:

from os.path import curdir


class Hello:
    def hey(self):
        return curdir

test_hello.py:

import unittest
from unittest import TestCase
from unittest.mock import patch
from hello import Hello


class TestHello(TestCase):
    @patch('hello.curdir', new='mock')
    def test_hey(self):
        h = Hello()
        res = h.hey()
        print(res)
        assert res == 'mock'


if __name__ == '__main__':
    unittest.main()

unit test result:

⚡  coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/66861243/test_hello.py && coverage report -m --include='./src/**'
mock
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Name                                       Stmts   Miss  Cover   Missing
------------------------------------------------------------------------
src/stackoverflow/66861243/hello.py            4      0   100%
src/stackoverflow/66861243/test_hello.py      13      0   100%
------------------------------------------------------------------------
TOTAL                                         17      0   100%
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Great thanks for this. I was looking for this for long time and couldn't understand my mistake. – Meroz Mar 30 '21 at 17:16