我正在尝试测试项目DRF的状态代码。
def test_status_code(client):
resp = client.get('/myapi/api/')
assert resp.status_code == 200
我希望输出200,但实际是401。
收到评论后,我尝试这样做:
import pytest
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
@pytest.fixture
def user():
token = Token.objects.get(user__username='foo')
client = APIClient()
user = client.credentials(HTTP_AUTHORIZATION='Token' + token.key)
return user
def test_view_status_code(client, user):
resp = client.get('/myapi/api/')
assert resp.status_code == 200
答案 0 :(得分:0)
首先在客户端上调用login()
方法:
def test_view_status_code(client, user):
username = 'foo'
password = 'bar'
user.objects.create_user(username=username, password=password)
client.login(username=username, password=password)
response = client.get('/myapi/api/')
assert resp.status_code == 200