![](/img/trans.png)
[英]Django rest framework unauthenticated user get request error in testing
[英]Testing in Django Rest Framework, reproduce this curl request?
我正在嘗試為Django Rest Framework運行一些測試(鏈接到測試),並重現此curl調用:
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>"
http://<client_id>:<client_secret>@127.0.0.1:8000/v1/token/
這是我嘗試過的:
def test_oauth2_token_for_user(self):
"""
Test Django OAuth Toolkit and make a request for am access token.
"""
self.client.credentials(HTTP_AUTHORIZATION='grant_type ' + "password&username=<user_name>&password=<password")
response = self.client.post('/api/token/')
有人可以告訴我從哪里開始。 我不確定如何發送標頭grant_type=password&username=<user_name>&password=<password>
並使用用戶名和密碼設置URL格式。
那不是標題。 這是完全正常的POST數據,正如測試客戶端文檔所示,您只需傳入字典作為post
的第二個參數即可。
response = self.client.post('/api/token/',
{'grant_type': 'password', 'username': username, 'password': password})
我找不到用django的test Client發送此數據並發送數據和授權數據的api的方法。
我的解決方案使用LiveServerTestCase( https://docs.djangoproject.com/en/1.10/topics/testing/tools/#liveservertestcase )進行了測試,並使用請求庫進行發布:
class AuthTest(LiveServerTestCase):
def test_auth(self):
# ...
requests.post(
http://localhost:8082/o/token/,
dict(username="myuser",
password="mypass",
grant_type="password"
),
auth=(MYAPP.client_id, MYAPP.client_secret)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.