pytest and factoryboy not associating the user tothe request object

38 Views Asked by At

Here is my test

import ipdb
import pytest
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
pytestmark = pytest.mark.django_db

class TestUrlEndpoints:

    def test_url_get(self, url_factory, api_client):
        api_client_1 = APIClient()
        url = url_factory()
        assert url.user.__str__() == "fake"
        token = Token.objects.create(user=url.user)
        assert url.user.is_authenticated is True
        ipdb.set_trace()
        api_client_1.credentials(HTTP_AUTHORIZATION="Token " + token.key)
        response = api_client_1.get("/api/url/")
        assert response.status_code == 200

The "assert url.user.is_authenticated is True" succeeds but

api_client_1.credentials(HTTP_AUTHORIZATION="Token " + token.key)

does not seem to work correctly because when I check the request down the line with request.user.str() then it shows 'AnonymousUser'.

the factories looks like this

    class CustomUserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = NewUser

    email = "[email protected]"
    user_name = "fake"
    first_name = "fake"
    password = "Asd!@34"


class UrlFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Url

    name = "www.aaa.com"
    user = factory.SubFactory(CustomUserFactory)
0

There are 0 best solutions below