[英]How to create a Django REST Framework View instance from a ViewSet class?
I'm trying to unit test Django REST Framework view set permissions for two reasons: speed and simplicity. 我试图对Django REST Framework视图集权限进行单元测试,原因有二:速度和简便性。 In keeping with these goals I would also like to avoid using any mocking frameworks.
为了实现这些目标,我还想避免使用任何模拟框架。 Basically I want to do something like this:
基本上我想做这样的事情:
request = APIRequestFactory().post(…)
view = MyViewSet.as_view(actions={"post": "create"})
self.assertTrue(MyPermission().has_permission(request, view))
The problem with this approach is that view
is not actually a View
instance but rather a function which does something with a View
instance, and it does not have certain properties which I use in has_permission
, such as action
. 这种方法的问题是,
view
实际上不是一个View
实例而是它做了一个功能 View
实例,它不具有某些特性,我在使用has_permission
,如action
。 How do I construct the kind of View
instance which can be passed to has_permission
? 如何构造可以传递给
has_permission
的View
实例?
The permission is already tested at both the integration and acceptance level, but I would like to avoid creating several complex and time-consuming tests to simply check that each of the relevant actions are protected. 权限已经在集成和接受级别上进行了测试,但是我想避免创建多个复杂且耗时的测试来简单地检查每个相关动作是否受到保护。
I've been able to work around this by monkeypatching a view set instance and manually dispatching it: 我可以通过猴子修补视图集实例并手动调度它来解决此问题:
view_set = MyViewSet()
view_set.action_map = {"post": "create"}
view_set.dispatch(request)
You can do something like below. 您可以执行以下操作。
request = APIRequestFactory().post(…)
view_obj = MyViewSet()
self.assertTrue(MyPermission().has_permission(request, view_obj))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.