我正在尝试对一个函数进行单元测试:
@shared_task()
def push_notification(message=None, message_type=None, user_id=None, data={}):
# Get the aws arn from token table
aws_token_data = AwsDeviceToken.objects.filter(user_id=user_id).latest("id")
client = boto3.client('sns', **aws.AWS_CREDENTIAL)
message = {
'default': message,
more stuff here
'data': data})
}
message = json.dumps(message, ensure_ascii=False)
response = client.publish(
TargetArn=str(aws_token_data.aws_PLATFORM_endpoint_arn),
Message=message,
MessageStructure='json',
MessageAttributes={}
)
return response
当用户注册我们的服务时,他们会根据其设备类型获得一个主题。
我已经尝试过:
def test_push_notification(self):
with mock.patch('boto3.client') as mock_client:
data = {'Some data': "to be sent"}
push_notification(
message="your invitation has been accepted",
message_type='b2g_accepted',
user=self.user,
data=data
)
self.assertEqual(mock_client.call_count, 1)
其中self.user是在TestCase的setUp方法中注册的用户。失败,call_count为0
我正在绞尽脑汁试图找到一种方法来测试这个功能,但主要是想出第三方模块或 S3 的示例。
感谢任何帮助
最佳答案
您需要模拟它的导入位置(除非它是类方法)
因此,如果您的 Push_notification 函数位于名为 my_module 的模块中,您应该编写:
With mock.patch('my_module.boto3.client') as mock_client
关于django - 如何在单元测试中模拟 boto3 sns 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40179132/