0

有没有人成功地在 Django 应用程序中为 Paddle webhook 编写测试?

Paddle 将消息作为 POST 请求发送到 webhook。根据Paddle 的 webhook 测试,示例请求如下所示:

[alert_id] => 1865992389
[alert_name] => payment_succeeded
[...] => ...

我的 Django 应用程序中的 webhook 将其作为request.POST=<QueryDict>参数接收:

{'alert_id': ['1865992389'], 'alert_name': ['payment_succeeded'], '...': ['...']}

也就是说,所有值都作为数组接收,而不是值。

相反,我的 webhook 测试看起来像我期望的消息格式,即使用值而不是数组:

    response = client.post('/pricing/paddlewebhook/',
                           {'alert_name': 'payment_succeeded',
                            'alert_id': '1865992389',
                            '...': '...',
                            },
                           content_type='application/x-www-form-urlencoded')
    assert response.status_code == 200  # Match paddle's expectation

这由 webhook 作为request.POST=<QueryDict>参数接收:

{'alert_name': 'payment_succeeded', 'alert_id': '1865992389', '...': '...'}

webhook 本身是基于类的视图的简单 POST 方法:

# Django wants us to apply the csrf_exempt decorator all methods via dispatch() instead of just to post().
@method_decorator(csrf_exempt, name='dispatch')
class PaddleWebhook(View):
    def post(self, request, *args, **kwargs):
        logger.info("request.POST=%s", request.POST)
        # ...

将测试(和视图)更改为包含数组值是否真的适合测试行为,post()或者我是否遗漏了一些关于对 POST webhook 的外部调用的明显内容?

4

1 回答 1

0

一个可能的解决方案(“为我工作”)是定义并使用中间方法来“调整”传入参数 dict:

    def _extractArrayParameters(self, params_dict: dict) -> dict:
        """Returns a parameter dict that contains values directly instead of single element arrays.
        Needed as messages from paddle are received as single element arrays.
        """
        ret = dict()
        for k, v in params_dict.items():
            # Convert all single element arrays directly to values.
            if isinstance(v, list) and len(v) == 1:
                ret[k] = v[0]
            else:
                ret[k] = v
        return ret

然而,这感觉很脏,即使它使所有测试都通过了。

于 2021-02-28T13:56:54.703 回答