繁体   English   中英

模拟python单元测试的问题

[英]Issue in mocking python unit test

我写了一个测试如下:

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

您的代码: from common.ds_factory import 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. 我在这里看到的问题是,数据存储不存在,它应该是 self.ds.read_file
  2. 请打印 self.datastore.read_file(S3_BUCKET, file_key) 并验证输出。
  3. 这是来自 AWS_S3 存储桶 Json 结构的错误。 它似乎不是以字符串格式而不是魔术模拟格式发送 Json 值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM