我读过一些关于Python模拟的教程,但我仍在努力:-/
例如,我有一个函数包装对Google存储的调用以编写Blob。
我想模拟google.storage.Client()。bucket(bucket_name)方法以返回exceptions.NotFound特定的不存在的存储桶。我正在使用side_effect设置例外
你知道我在做什么错吗?
以下是我尝试过的方法(我正在使用2个文件:main2.py和main2_test.py):
# main2.py
import logging
from google.cloud import storage
def _write_content(bucket_name, blob_name, content):
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
try:
blob.upload_from_string(data=content)
return True
except Exception:
logging.error("Failed to upload blob")
raise
和
# main2_test.py
import pytest
from unittest.mock import patch
from google.api_core import exceptions
import main2
@patch("main2.storage.Client", autospec=True)
def test_write_content(clientMock):
bucket_name = "not_existent_bucket"
clientMock().bucket(bucket_name).side_effect = exceptions.NotFound
with pytest.raises(exceptions.NotFound):
main2._write_content(bucket_name, "a_blob_name", '{}')
通话范例
pytest main2_test.py::test_write_content
结果
platform linux -- Python 3.7.7, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: /home/user/project, inifile: pytest.ini
plugins: requests-mock-1.8.0
collected 1 item
main2_test.py::test_write_content FAILED [100%]
============================================================================================== FAILURES ==============================================================================================
_________________________________________________________________________________________ test_write_content _________________________________________________________________________________________
clientMock = <MagicMock name='Client' spec='Client' id='139881522497360'>
@patch("main2.storage.Client", autospec=True)
def test_write_content(clientMock):
bucket_name = "my_bucket"
clientMock().bucket(bucket_name).side_effect = exceptions.NotFound
with pytest.raises(exceptions.NotFound):
> main2._write_content(bucket_name, "a_blob_name", '{}')
E Failed: DID NOT RAISE <class 'google.api_core.exceptions.NotFound'>
main2_test.py:14: Failed
=====================================
FAILED main2_test.py::test_write_content - Failed: DID NOT RAISE <class 'google.api_core.exceptions.NotFound'>
=====================================
您的测试有两个问题:您没有在模拟应该实际引发(upload_from_string
)的方法,而是在设置异常类而不是产生副作用的异常。
以下将起作用:
@patch("main2.storage.Client", autospec=True)
def test_write_content(clientMock):
blob_mock = clientMock().bucket.return_value.blob.return_value # split this up for readability
blob_mock.upload_from_string.side_effect = exceptions.NotFound('testing') # the exception is created here
with pytest.raises(exceptions.NotFound):
main2._write_content("not_existent", "a_blob_name", '{}')
还要注意,为bucket
调用设置特定参数没有任何效果,因为它是在模拟中调用的,并且该参数只是被忽略了-我用替换了它return_value
,这使它更清晰。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句