测试POST方法到Django REST视图集

时间:2017-11-18 05:13:11

标签: python django rest testing

文档仅说GET

的映射
  

user_list = UserViewSet.as_view({' get':' list'})
  user_detail = UserViewSet.as_view({' get':' retrieve'})

tests.py

def test_admin_can_create_role(userprofiles, aoo_admin, bug_manager, note_admin):
    aoo = User.objects.get(username='aoo')
    factory = APIRequestFactory()
    view = RoleViewSet.as_view()
    url = reverse('api:role-list')
    data = {
        'name': 'FirstAdmin',
        'type': Role.RoleType.admin,
        'company': 1,
    }
    request = factory.post(url, data=data, format='json')
    force_authenticate(request, user=aoo)
    response = view(request)
    assert 201 == response.data

viewsets.py

class RoleViewSetPermission(permissions.BasePermission):
    message = 'Only Manager or Admin are allowed'

    def has_permission(self, request, view):
        user = request.user
        return user.has_perm('roles.add_role') \
               and user.has_perm('roles.change_role') \
               and user.has_perm('roles.delete_role')


class RoleViewSet(viewsets.ModelViewSet):
    permission_classes = (RoleViewSetPermission,)
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    filter_backends = (filters.DjangoFilterBackend, SearchFilter)
    filter_class = RoleFilter
    search_fields = ('name', 'description', 'user__username', 'company__name', 'company__name_th')

    def filter_queryset(self, queryset):
        try:
            company = self.request.user.user_profile.companyappid.company
        except AttributeError:
            logger.error(f'{self.request.user} has AttributeError')
            return Role.objects.none()
        else:
            logger.info(f'{self.request.user} is {company} member')
            return queryset.filter(company=company)

引用:

cls = <class 'poinkbackend.apps.roles.api.viewsets.RoleViewSet'>, actions = None, initkwargs = {}

    @classonlymethod
    def as_view(cls, actions=None, **initkwargs):
        """
            Because of the way class based views create a closure around the
            instantiated view, we need to totally reimplement `.as_view`,
            and slightly modify the view function that is created and returned.
            """
        # The suffix initkwarg is reserved for identifying the viewset type
        # eg. 'List' or 'Instance'.
        cls.suffix = None

        # actions must not be empty
        if not actions:
>           raise TypeError("The `actions` argument must be provided when "
                            "calling `.as_view()` on a ViewSet. For example "
                            "`.as_view({'get': 'list'})`")
E           TypeError: The `actions` argument must be provided when calling `.as_view()` on a ViewSet. For example `.as_view({'get': 'list'})`

../../.pyenv/versions/3.6.3/envs/poink/lib/python3.6/site-packages/rest_framework/viewsets.py:55: TypeError

问题:
如何对force_authenticate request.postviewsets进行操作? 我没有问题。它已在SO

中得到答案

参考文献:
http://www.django-rest-framework.org/api-guide/viewsets/

1 个答案:

答案 0 :(得分:1)

我必须使用APIClient而不是APIRequestFactory 我虽然只有一种方法可以进行测试。
这是我的例子。

def test_admin_can_create_role(userprofiles, aoo_admin, bug_manager, note_admin):
    aoo = User.objects.get(username='aoo')
    client = APIClient()
    client.force_authenticate(user=aoo)
    url = reverse('api:role-list')
    singh = Company.objects.get(name='Singh')
    data = {
        'name': 'HairCut',
        'type': Role.RoleType.admin,
        'company': singh.id,  # Must be his companyid. Reason is in the RoleSerializer docstring
    }
    response = client.post(url, data, format='json')

    assert 201 == response.status_code