我写了如下测试:
class TestLoader(TestCase):
@pytest.fixture(autouse=True)
@patch('loaders.myloader.DSFactory')
def _initialize_(self, mock_ds_factory):
self.loader = MyLoader()
mock_ds = Mock()
mock_ds_factory.get_ds_for_env.return_value = mock_ds
self.loader.ds = mock_ds
def test_load(self):
self.loader.ds.read_file.return_value = json.dumps(self.get_data())
self.loader.load("test_s3_key") #####IN THIS LINE I AM GETTING ERROR AS MENTIONED BELOW##
@staticmethod
def get_data():
return {"key1":"value1","key2":"value2"}
相关源位于此处:loaders-> myloader.py。 myloader.py如下:
from common.ds_factory import DSFactory
class MyLoader:
def __init__(self):
self.ds = DSFactory.get_ds_for_env()
def load(self, file_key):
print(f"ds : {self.ds}")
print(f"file read is : {self.ds.read_file(S3_BUCKET, file_key)}"}
data_dict = json.loads(self.ds.read_file(S3_BUCKET, file_key))
但是在测试时,出现如下错误:
ds is :<MagicMock name='DSFactory.get_ds_for_env()' id='140634163567528'>
file read is :<MagicMock name='DSFactory.get_ds_for_env().read_file()' id='140635257259568'>
E TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock'
即使在用
模拟read_file的返回值后,我也不明白为什么self.loader.ds.read_file.return_value = json.dumps(self.get_data())
我正在获取MagickMock
对象。我被困住了,不知道如何解决这个问题。
答案 0 :(得分:1)
您的代码: 从common.ds_factory导入DSFactory
class MyLoader:
def __init__(self):
self.ds = DSFactory.get_ds_for_env()
def load(self, file_key):
data_dict = json.loads(self.datastore.read_file(S3_BUCKET, file_key))
要详细了解Magic Mock格式,请访问此处:https://medium.com/ryans-dev-notes/python-mock-and-magicmock-b3295c2cc7eb