Search code examples
pythondjangounit-testingfixtures

Get jwt token to pass it to unit test


I'm trying to retreive jwt access token to pass it to unit test but everytime I try to get it I receive 'not authorized' error. User is created in database with factory

#factories.py

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = "test_user"
    password = "test123"
    date_of_birth = "2000-01-22"
    email = "tests@test.ru"
    role = "moderator"

class AdFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Ad

    name = "test"
    author_id = factory.SubFactory(UserFactory)
    price = 100
    description = "None"
    is_published = "FALSE"
    category = factory.SubFactory(CategoryFactory)
    image = None

And I', trying to get jwt access token in fixtures.py

# fixtures.py

import pytest


@pytest.fixture
@pytest.mark.django_db
def user_token_jwt(client):
    username = "test_user"
    password = "test123"

    response = client.post(
        "/user/token/",
        {"username": username, "password": password},
        format="json"
    )
    print(response.data)

    return response.data["access"]

Finally, the test function itself. Please help me to understand how to retrieve a jwt access token in Django with such project architecture?

@pytest.mark.django_db
def test_create_ad(client, ad, user_token_jwt):
    # user_token_jwt = client.post(
    #     "/user/token/",
    #     {"username": "test_user", "password": "test123"},
    #     content_type="application/json"
    # )

    expected_response = {
        'id': ad.pk,
        'name': 'test',
        'author_id': ad.author_id_id,
        'author': ad.username,
        'price': 100,
        'description': 'None',
        'is_published': 'FALSE',
        'category_id': ad.category_id,
        'image': None
    }

    data = {
        "name": "test",
        "price": 100,
        "description": "None",
        "author_id": ad.author_id,
        "category": ad.category_id,
    }
    response = client.post(
        "/ad/create/",
        data,
        content_type='application/json',
        HTTP_AUTHORIZATION="Bearer" + user_token_jwt
    )

    assert response.status_code == 201
    assert response.data == expected_response

Solution

  • I'm not an expert in django or pytest. I was even inspired by your code to write mine. THANKS ;) To validate your test with the access token, did you simply add a space behind Bearer? HTTP_AUTHORIZATION="Bearer " instead of "Bearer". It works for me