开发者社区> 问答> 正文

模拟python单元测试中的问题

我写了如下测试:

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对象。我被困住了,不知道如何解决这个问题。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 21:31:31 569 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))
    
    1. Issue here i can see is, data-store is not present, it should be self.ds.read_file
    2. Please print self.datastore.read_file(S3_BUCKET, file_key) and verify the output.
    3. This is the error coming from AWS_S3 bucket Json structure. It seems its not sending the Json value in string format rather than in Magic Mock format.

    有关Magic Mock格式的更多信息,请访问此处:https : //medium.com/ryans-dev-notes/python-mock-and-magicmock-b3295c2cc7eb

    回答来源:stackoverflow

    2020-03-24 21:31:37
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载