mock.patch 的 Pytest 不会模拟 os.path.curdir
Pytest with mock.patch does not mock os.path.curdir
我正在尝试模拟 os.path.curdir
所以它 returns 给出 return_value
但这不起作用。
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'
我错过了什么?
您应该为 hello.py
模块修补 curdir
变量。所以打补丁的目标应该是hello.curdir
。有关详细信息,请参阅 where-to-patch。
例如
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()
单元测试结果:
⚡ coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/Whosebug/66861243/test_hello.py && coverage report -m --include='./src/**'
mock
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Name Stmts Miss Cover Missing
------------------------------------------------------------------------
src/Whosebug/66861243/hello.py 4 0 100%
src/Whosebug/66861243/test_hello.py 13 0 100%
------------------------------------------------------------------------
TOTAL 17 0 100%
我正在尝试模拟 os.path.curdir
所以它 returns 给出 return_value
但这不起作用。
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'
我错过了什么?
您应该为 hello.py
模块修补 curdir
变量。所以打补丁的目标应该是hello.curdir
。有关详细信息,请参阅 where-to-patch。
例如
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()
单元测试结果:
⚡ coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/Whosebug/66861243/test_hello.py && coverage report -m --include='./src/**'
mock
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Name Stmts Miss Cover Missing
------------------------------------------------------------------------
src/Whosebug/66861243/hello.py 4 0 100%
src/Whosebug/66861243/test_hello.py 13 0 100%
------------------------------------------------------------------------
TOTAL 17 0 100%