Search code examples
pythondjango-rest-frameworkpytestpytest-djangopytest-cov

TypeError: 'Token' object is not callable


When I test the test_delivery.py with pytest, I get the error: "TypeError: 'Token' object is not callable".

I am using pytest with Django REST. From the examples that I saw, it seems that the code is correct. What am I missing?

basic.py

import pytest

@pytest.fixture
def api_client():
   from rest_framework.test import APIClient
   return APIClient()

@pytest.fixture
def test_password():
   return 'Str0ng-test-pa$$'

import uuid

@pytest.fixture
def create_user(db, django_user_model, test_password):
   def make_user(**kwargs):
       kwargs['password'] = test_password
       if 'username' not in kwargs:
           kwargs['username'] = str(uuid.uuid4())
       return django_user_model.objects.create_user(**kwargs)
   return make_user


from rest_framework.authtoken.models import Token

@pytest.fixture
def get_or_create_token(db, create_user):
   user = create_user()
   token, _ = Token.objects.get_or_create(user=user)
   return token

test_delivery.py

import pytest

from django.urls import reverse
from tests.utils.basic import api_client, get_or_create_token, create_user, test_password
from rest_framework.authtoken.models import Token


@pytest.mark.django_db
def test_unauthorized_request(api_client):
   url = reverse('deliveries-list')
   response = api_client.get(url)
   assert response.status_code == 401

@pytest.mark.django_db
def test_authorized_request(api_client, get_or_create_token):
   url = reverse('deliveries-list')
   token = get_or_create_token()
   api_client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
   response = api_client.get(url)
   assert response.status_code == 200

[Update] Error details

======================================================= FAILURES =======================================================
_______________________________________________ test_authorized_request ________________________________________________

api_client = <rest_framework.test.APIClient object at 0x7f1ee5e0fa00>
get_or_create_token = <Token: 1771cc20278aed83af8e09646286edd1ef8cb7b7>

    @pytest.mark.django_db
    def test_authorized_request(api_client, get_or_create_token):
       url = reverse('deliveries-list')
>      token = get_or_create_token()
E      TypeError: 'Token' object is not callable

tests/test_delivery/test_delivery.py:17: TypeError

Solution

  • This is the new test_authorized_request that worked for me. I changed the way that I created the token.

    test_delivery.py

    @pytest.mark.django_db
    def test_authorized_request(api_client, get_or_create_token): 
       user = User.objects.create_user('test', '[email protected]', 'Strong-test-pass')
       token = Token.objects.create(user=user)
       url = reverse('deliveries-list')
       api_client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
       response = api_client.get(url)
       assert response.status_code == 200