简体   繁体   English

如何在 Django 单元测试中模拟装饰器?

[英]How to mock decorator in django unit test?

I am trying to write simple unit test for my view.我正在尝试为我的视图编写简单的单元测试。 I have a decorator which authenticate by sending http request.我有一个装饰器,它通过发送 http 请求进行身份验证。 How to mock decorator of my view and run unit test?如何模拟我的视图的装饰器并运行单元测试?

my views.py我的意见.py

@method_decorator(authentication_decorator, name='post')
class AddBlogView(CreateAPIView):
    serializer_class = BlogSerializer

Try this (adapt the code for your app and file names):试试这个(调整你的应用程序和文件名的代码):

from mock import patch
patch('app.decorators.authentication_decorator', lambda x: x).start()  # This line must come before other imports

from app.views import AddBlogView
# Test AddBlogView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM