2014-09-30 68 views
0

我試圖運行Django Rest Framework(鏈接測試)一些測試和重現此捲曲電話:在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>並使用用戶名和密碼格式化網址。

回答

2

這不是一個標題。這是完全正常的POST數據,正如test client documentation所顯示的那樣 - 您可以將字典作爲第二個參數傳遞給post

response = self.client.post('/api/token/', 
     {'grant_type': 'password', 'username': username, 'password': password}) 
0

我無法找到一個方法來發布到這個API與Django的測試客戶端發送POST數據和授權數據。

我的解決辦法是設定LiveServerTestCase(https://docs.djangoproject.com/en/1.10/topics/testing/tools/#liveservertestcase)測試,並使用POST請求庫:

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) 
     )