Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to add token headers to graphene-django test using pytest #1379

Open
saadshehzad opened this issue Oct 4, 2021 · 1 comment
Open
Labels

Comments

@saadshehzad
Copy link

saadshehzad commented Oct 4, 2021

I am trying to add token to graphene-django headers using pytest. But It always return that user is anonymous as shown at the end but it should return user as token is added in fixture

@pytest.fixture
def create_candidate(candidate_factory):
    candidate = []
    for _ in range(5):
        can = candidate_factory.create()
        token, __ = Token.objects.get_or_create(user=can.user)
        candidate.append(can)

    return candidate

**This is the test**
@pytest.mark.django_db
def test_get_login_candidate(client_query, create_candidate):
    headers = {"Authorization": f"Token {create_candidate[0].user.auth_token}"}
    response = client_query(
        """
        query {
          loginCandidate{
              id,
          }
        }
        """,
        headers=headers,
    )

    result = json.loads(response.content)
    print(result)


This is the output

{'errors': [{'message': "'AnonymousUser' object is not iterable", 'locations': [{'line': 3, 'column': 11}], 'path': ['loginCandidate']}], 'data': {'loginCandidate': None}}
@Ronjea
Copy link

Ronjea commented Apr 19, 2022

import pytest
from base.middlewares import DataLoaderMiddleware
from django.test import RequestFactory, TestCase
from graphene.test import Client
from mixer.backend.django import mixer

from wheretheschema import schema

ME = """
query me {
    me {
        id
        firstName
        lastName
        phone
        token
    }
}
"""


@pytest.mark.django_db
class TestExampleGithub(TestCase):
    def setUp(self):
        request_factory = RequestFactory()
        self.client = Client(schema)
        self.my_request = request_factory.get("/api/")
        self.user = mixer.blend(User, phone="123456789")

    def test_me(self):
        self.my_request.user = self.waiter
        response = self.client.execute(
            ME, context_value=self.my_request, middleware=[DataLoaderMiddleware()]
        )
        data = response.get("data").get("me")
        assert data.get("phone") == "123456789"
        assert data.get("token") is not None

If that works with you this is how I'm doing this.

I do not think this is an issue it will be more a doubt than an issue I hope it works for you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants