[Python] How can I correctly pass arguments to classbasedviews testing the Django REST...

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I want to test some views in the Django REST Framework (DRF) project.

    The problem comes when I try to check views that have arguments in the URLs.

    File urls.py



    url(r'^(?Pcompany_hash>[\d\w]+)/(?Ptimestamp>[\.\d]*)/employees/$',
    EmployeeList.as_view(), name='employeelist'),



    ("<" in URLs has been deleted on purpose. Just it isnt considered a tag and thus is not shown)

    File views.py



    class EmployeeList(ListCreateAPIView):
    serializer_class = EmployeeDirectorySerializer

    def inner_company(self):
    company_hash = self.kwargs['company_hash']
    return get_company(company_hash)

    def get_queryset(self):
    return Employee.objects.filter(company=self.inner_company())

    File test.py




    class ApiTests(APITestCase):
    def setUp(self):
    self.factory = APIRequestFactory()
    self.staff = mommy.make('directory.Employee', user__is_staff=True)
    self.employee = mommy.make('directory.Employee')

    self.hash = self.employee.company.company_hash

    def getResponse(self, url, myView, kwargs):
    view = myView.as_view()
    request = self.factory.get(url, kwargs)

    force_authenticate(request, user=user)

    response = view(request)
    return response

    def test_EmployeeList(self):
    kwargs = {'timestamp': 0, 'company_hash': self.hash}
    url = reverse('employeelist', kwargs=kwargs)
    testedView = EmployeeList

    response = self.getResponse(url, testedView,
    kwargs=kwargs)
    self.assertEqual(response.status_code, 200)


    I'm getting this error:


    company_hash = self.kwargs['company_hash']
    KeyError: 'company_hash'


    That is, the args aren't been passed to the view.

    I've tried in so many different ways to pass by the args, but I can't find a solution.

    Continue reading...

Compartilhe esta Página