【发布时间】:2015-11-09 11:01:57
【问题描述】:
我创建了一个名为/cars 的端点。
一个人可以使用前端创建汽车,但设备读取汽车使用具有 API 密钥的 SDK。这样,两家租车公司就可以使用 API 而不会混淆汽车。每个应用都有自己的 API 密钥和自己的内容管理人员。
这是通过 django restframework 3.x 和 django-oauth-toolkit 实现的。
我正在为人类检索汽车和另一个设备编写测试。
这失败了:
def test_get_list(self):
# devices have a django user (AUTH_USER_MODEL ---onetoone--- Device)
self.client.force_authenticate(user=self.user_device)
self._get_list()
self.client.force_authenticate(user=None)
force_authentication 将 request.auth 设置为 None。但是,对于 postman 或 httpie,request.auth 包含 Application 对象。
查询集是:
def get_queryset(self):
if hasattr(self.request.user, 'device'):
# get the cars created by the owner of the API Key
return self.request.auth.application.user.cars.all()
return self.request.user.cars.all() # get my cars
- 查询集中的这种方法有意义吗?
- 我是否以错误的方式测试它?
- 为什么 request.auth 为空? force_authentication 是否使用 BasicAuthentication?
【问题讨论】:
标签: django unit-testing django-rest-framework