为什么我不能为我的单元测试从不同的文件中修补 class?
Why can't I patch a class from a different file for my unit test?
我有一个名为 some.py
的文件:
from dataclasses import dataclass
from some_folder.some_reader import SomeReader
class SomeClass:
def __init__(self, url):
self.reader = SomeReader(url)
和some_reader.py
:
class SomeReader:
def read_path(self, url):
return "read_path"
和some_test.py
:
from unittest.mock importpatch
from some_folder.some import SomeClass
@patch("some_folder.some_reader.SomeReader")
def test_some_class(mock_some_reader):
SomeClass("")
当我运行some_test
时,似乎实例化的SomeReader
不是模拟对象,而是:
SomeReader
<class 'some_folder.some_reader.SomeReader'>
如果我把 SomeReader
放在 some.py
中似乎一切正常。
some.py
:
from some_folder.some_reader import SomeReader
class SomeClass:
def __init__(self, url):
self.reader = SomeReader(url)
some_folder/some_reader.py
:
class SomeReader:
def read_path(self, url):
return "read_path"
test_some.py
:
import unittest
from unittest.mock import patch
from some import SomeClass
class TestSome(unittest.TestCase):
@patch("some.SomeReader")
def test_some_class(self, mock_some_reader):
some = SomeClass("")
print(some.reader)
if __name__ == '__main__':
unittest.main()
测试结果:
<MagicMock name='SomeReader()' id='4520784368'>
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
我有一个名为 some.py
的文件:
from dataclasses import dataclass
from some_folder.some_reader import SomeReader
class SomeClass:
def __init__(self, url):
self.reader = SomeReader(url)
和some_reader.py
:
class SomeReader:
def read_path(self, url):
return "read_path"
和some_test.py
:
from unittest.mock importpatch
from some_folder.some import SomeClass
@patch("some_folder.some_reader.SomeReader")
def test_some_class(mock_some_reader):
SomeClass("")
当我运行some_test
时,似乎实例化的SomeReader
不是模拟对象,而是:
SomeReader
<class 'some_folder.some_reader.SomeReader'>
如果我把 SomeReader
放在 some.py
中似乎一切正常。
some.py
:
from some_folder.some_reader import SomeReader
class SomeClass:
def __init__(self, url):
self.reader = SomeReader(url)
some_folder/some_reader.py
:
class SomeReader:
def read_path(self, url):
return "read_path"
test_some.py
:
import unittest
from unittest.mock import patch
from some import SomeClass
class TestSome(unittest.TestCase):
@patch("some.SomeReader")
def test_some_class(self, mock_some_reader):
some = SomeClass("")
print(some.reader)
if __name__ == '__main__':
unittest.main()
测试结果:
<MagicMock name='SomeReader()' id='4520784368'>
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK