我正在尝试对一个函数进行单元测试:
@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
当用户注册我们的服务时,他们会根据设备类型获得一个主题arn。
我试过了:
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的第三方模块或示例。
感谢任何帮助
答案 0 :(得分:1)
您需要模拟导入的位置(除非它是类方法)
因此,如果你的push_notification函数在一个名为my_module的模块中,你应该写:
With mock.patch('my_module.boto3.client') as mock_client