【发布时间】:2015-10-03 01:25:48
【问题描述】:
我想测试 DRF 项目中的一些视图。
当我尝试检查在 url 中有参数的视图时,问题就出现了。
urls.py
url(r'^(?Pcompany_hash>[\d\w]+)/(?Ptimestamp>[\.\d]*)/employees/$', EmployeeList.as_view(), name='employeelist'),[编辑:url中的“
views.py
EmployeeList 类(ListCreateAPIView): serializer_class= EmployeeDirectorySerializer def inner_company(self): company_hash = self.kwargs['company_hash'] 返回 get_company(company_hash) def get_queryset(self): 返回 Employee.objects.filter(company=self.inner_company())test.py
类 ApiTests(APITestCase): 默认设置(自我): 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): 视图 = myView.as_view() 请求 = self.factory.get(url, kwargs) force_authenticate(请求,用户=用户) 响应 = 查看(请求) 返回响应 def test_EmployeeList(self): kwargs = {'timestamp': 0, 'company_hash': self.hash} url = reverse('员工列表', kwargs=kwargs) 测试视图 = EmployeeList 响应 = self.getResponse(url, 测试视图, kwargs=kwargs) self.assertEqual(response.status_code, 200)我收到了这个错误
company_hash = self.kwargs['company_hash'] KeyError:'company_hash'也就是说参数没有被传递给视图。
我尝试了很多不同的方法来传递参数,但找不到解决方案。
欢迎任何帮助!
【问题讨论】:
-
您的
urls.py
输入错误。试试url(r'^(?P<company_hash>[\d\w]+)/(?P<timestamp>[\.\d]*)/employees/$', EmployeeList.as_view(), name='employeelist'),
-
感谢 Pynchia,但只是退出
标签: python django testing django-rest-framework