Cus*_*Bun 8 python python-unittest python-unittest.mock moto
I am currently trying to write unit tests for my python code using Moto & @mock_dynamodb2 . So far it's been working for me to test my "successful operation" test cases. But I'm having trouble getting it to work for my "failure cases".
In my test code I have:
@mock_dynamodb2
class TestClassUnderTestExample(unittest.TestCase):
def setUp(self):
ddb = boto3.resource("dynamodb", "us-east-1")
self.table = ddb.create_table(<the table definition)
self.example_under_test = ClassUnderTestExample(ddb)
def test_some_thing_success(self):
expected_response = {<some value>}
assert expected_response = self.example_under_test.write_entry(<some value>)
def test_some_thing_success(self):
response = self.example_under_test.write_entry(<some value>)
# How to assert exception is thrown by forcing put item to fail?
Run Code Online (Sandbox Code Playgroud)
The TestClassUnderTestExample would look something like this:
class ClassUnderTestExample:
def __init__(self, ddb_resource=None):
if not ddb_resource:
ddb_resource = boto3.resource('dynamodb')
self.table = ddb_resource.Table(.....)
def write_entry(some_value)
ddb_item = <do stuff with some_value to create sanitized item>
response = self.table.put_item(
Item=ddb_item
)
if pydash.get(response, "ResponseMetadata.HTTPStatusCode") != 200:
raise SomeCustomErrorType("Unexpected response from DynamoDB when attempting to PutItem")
return ddb_item
Run Code Online (Sandbox Code Playgroud)
I've been completely stuck when it comes to actually mocking the .put_item operation to return a non-success value so that I can test that the ClassUnderTestExample will handle it as expected and throw the custom error. I've tried things like deleting the table before running the test, but that just throws an exception when getting the table rather than an executed PutItem with an error code.
I've also tried putting a patch for pydash or for the table above the test but I must be doing something wrong. I can't find anything in moto's documentation. Any help would be appreciated!
小智 2
Moto 的目标是完全模仿 AWS 的行为,包括当用户提供错误输入时如何表现。换句话说,对 put_item() 的调用如果针对 AWS 失败,那么针对 Moto 也会/应该失败。
没有内置方法可以强制对有效输入做出错误响应。
从您的示例中很难看出如何强制执行此操作,但看起来值得使用此行来创建无效输入:
ddb_item = <do stuff with some_value to create sanitized item>
| 归档时间: |
|
| 查看次数: |
9166 次 |
| 最近记录: |