Python 另一个文件中的函数不会被模拟
我在一个名为local.py的文件中有这个类:Python 另一个文件中的函数不会被模拟,python,django,unit-testing,mocking,python-unittest,Python,Django,Unit Testing,Mocking,Python Unittest,我在一个名为local.py的文件中有这个类: 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
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()
它所做的只是返回传递给它的凭据
我想模拟我有另一个文件test\u local.py的get\u credentials
函数:
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()
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
它向我吐出“不是json”的事实表明它没有接受模拟值。我不明白它为什么这样做,因为我觉得我已经遵循了文档。如果您能提供一些帮助来解释为什么它不会被嘲笑,我们将不胜感激。您的代码中有一些拼写错误:您忘记了补丁装饰程序的
@
,补丁名称错误,您将函数结果而不是函数传递给new
。以下是固定测试的相关部分:
类名TestCase(unittest.TestCase):
@修补程序('local.get\u凭据',new=mock\u get\u凭据)
def测试(自身):
inst=ClassA()
仪器运行()
self.assertEqual(1,1)