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

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

    username = "test_user"
    password = "test123"
    date_of_birth = "2000-01-22"
    email = ""
    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


import pytest

def user_token_jwt(client):
    username = "test_user"
    password = "test123"

    response =
        {"username": username, "password": password},


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

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

    expected_response = {
        '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 =
        HTTP_AUTHORIZATION="Bearer" + user_token_jwt

    assert response.status_code == 201
    assert == expected_response

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

Back to Top