python - 我如何正确地将参数传递给测试 Django Rest Framework 的 classbasedviews?

标签 python django testing django-rest-framework

我想在 DRF 项目中测试一些 View 。

当我尝试检查在 url 中有参数的 View 时,问题就来了。

网址.py


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

[编辑:url 中的“<”已被故意删除,只是它不被视为标签,因此未显示]

View .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())

测试.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)

我遇到了这个错误

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

那是参数没有传递给 View 。

我尝试了很多不同的方法来传递参数,但找不到解决方案。

欢迎任何帮助!

最佳答案

检查您的 URL conf 中的正则表达式语法。您没有正确捕获命名组。你有

(?<P 

而不是

(?P<

https://docs.djangoproject.com/en/1.8/topics/http/urls/#named-groups

-詹姆斯

关于python - 我如何正确地将参数传递给测试 Django Rest Framework 的 classbasedviews?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31406106/

相关文章:

python - Django 1.8 不使用 Jinja2 模板引擎

python - 在 Django 1.10 中使用 Postgres 搜索时出现 NotImplementedError

python - Syncano v4 错误 : "You do not have permission to perform this action"

python - 有没有办法应用一个 numpy 函数,该函数将两个一维数组作为两个二维数组的每一行的参数?

python - 如何在 Python 中解析 RSS feed 中的 HTML 标签

django - 如何在 Django admin 中使用不同的表单小部件?

python - 如何在 Python 设置脚本中引入 importlib.resources

git 预推 : connection closed by remote host while running tests

django - 如何测试 Django 装饰器?

Spring mvc junit 测试服务