另一个文件中的函数不会被嘲笑
function in another file wont get mocked
我在名为 local.py 的文件中有此 class:
def get_credentials(creds):
data = creds
return data
class ClassA:
def __init__(self):
body = "not a json"
self.credentials = get_credentials(body)
def run(self):
print(self.credentials)
def main():
inst = ClassA()
inst.run()
if __name__ == "__main__":
main()
它所做的只是 return 传递给它的凭据。
我想模拟 get_credentials
函数,我有另一个文件 test_local.py:
from local import ClassA
import unittest
from unittest.mock import patch
def mock_get_credentials(creds):
return "123"
class NameTestCase(unittest.TestCase):
patch('local.get_credessntials', new=mock_get_credentials("test"))
def test_whatever(self):
print("true")
inst = ClassA()
inst.run()
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
我不断得到的输出是这样的:
true
not a json
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
它向我吐出 "not a json"
的事实表明它没有接受模拟值。我不明白为什么要这样做,因为我觉得我已经遵循了文档。对于为什么它没有被嘲笑,我将不胜感激。
您的代码中有一些拼写错误:您忘记了补丁装饰器的 @
,补丁名称错误,并且您将函数结果而不是函数传递给 new
。下面是固定测试的相关部分:
class NameTestCase(unittest.TestCase):
@patch('local.get_credentials', new=mock_get_credentials)
def test_whatever(self):
inst = ClassA()
inst.run()
self.assertEqual(1, 1)
我在名为 local.py 的文件中有此 class:
def get_credentials(creds):
data = creds
return data
class ClassA:
def __init__(self):
body = "not a json"
self.credentials = get_credentials(body)
def run(self):
print(self.credentials)
def main():
inst = ClassA()
inst.run()
if __name__ == "__main__":
main()
它所做的只是 return 传递给它的凭据。
我想模拟 get_credentials
函数,我有另一个文件 test_local.py:
from local import ClassA
import unittest
from unittest.mock import patch
def mock_get_credentials(creds):
return "123"
class NameTestCase(unittest.TestCase):
patch('local.get_credessntials', new=mock_get_credentials("test"))
def test_whatever(self):
print("true")
inst = ClassA()
inst.run()
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
我不断得到的输出是这样的:
true
not a json
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
它向我吐出 "not a json"
的事实表明它没有接受模拟值。我不明白为什么要这样做,因为我觉得我已经遵循了文档。对于为什么它没有被嘲笑,我将不胜感激。
您的代码中有一些拼写错误:您忘记了补丁装饰器的 @
,补丁名称错误,并且您将函数结果而不是函数传递给 new
。下面是固定测试的相关部分:
class NameTestCase(unittest.TestCase):
@patch('local.get_credentials', new=mock_get_credentials)
def test_whatever(self):
inst = ClassA()
inst.run()
self.assertEqual(1, 1)