我有一个核心类,我试图在那里读取zip文件,解压缩,获取一个特定的文件,并获得该文件的内容。这工作得很好,但现在我试图模拟我在这一过程中使用的所有东西。
class ZipService:
def __init__(self, path: str):
self.path = path
def get_manifest_json_object(self):
s3 = boto3.resource('s3')
bucket_name, key = self.__get_bucket_and_key()
bucket = s3.Bucket(bucket_name)
zip_object_reference = bucket.Object(key).get()["Body"]
zip_object_bytes_stream = self.__get_zip_object_bytes_stream(zip_object_reference)
zipf = zipfile.ZipFile(zip_object_bytes_stream, mode='r')
return self.__get_manifest_json(zipf)
def __get_bucket_and_key(self):
pattern = "https:\/\/(.?[^\.]*)\.(.?[^\/]*)\/(.*)" # this regex is working but don't know how :D
result = re.split(pattern, self.path)
return result[1], result[3]
def __get_zip_object_bytes_stream(self, zip_object_reference):
return io.BytesIO(zip_object_reference.read())
def __get_manifest_json(self, zipf):
manifest_json_text = [zipf.read(name) for name in zipf.namelist() if "/manifest.json" in name][0].decode("utf-8")
return json.loads(manifest_json_text)
为此,我编写了一个抛出错误的测试用例:
@patch('boto3.resource')
class TestZipService(TestCase):
def test_zip_service(self, mock):
s3 = boto3.resource('s3')
bucket = s3.Bucket("abc")
bucket.Object.get.return_value = "some-value"
zipfile.ZipFile.return_value = "/some-path"
inst = ZipService("/some-path")
with mock.patch.object(inst, "_ZipService__get_manifest_json", return_value={"a": "b"}) as some_object:
expected = {"a": "b"}
actual = inst.get_manifest_json_object()
self.assertIsInstance(expected, actual)
错误:
bucket_name, key = self.__get_bucket_and_key()
File "/Us.tox/py38/lib/python3.8/site-packages/services/zip_service.py", line 29, in __get_bucket_and_key
return result[1], result[3]
IndexError: list index out of range
这里到底出了什么问题?任何提示也将不胜感激。TIA
1条答案
按热度按时间mctunoxg1#
您正在为
ZipService
指定一个路径"/some-path"
。然后测试它的
get_manifest_json_object
方法,该方法的第二条语句调用__get_bucket_and_key
。您没有模仿
__get_bucket_and_key
,所以当调用它时,它会尝试使用正则表达式拆分来处理输入路径,这不会给您提供return result[1], result[3]
所需的包含4个项的集合。因此,
IndexError: list index out of range
。要么给予
ZipService
一个您期望的正确路径,要么模拟get_manifest_json_object
中使用的所有私有方法。