Last active
February 27, 2020 09:32
-
-
Save wolkenarchitekt/1c1784ad6592bd7a20f884d7ac1a67f3 to your computer and use it in GitHub Desktop.
Using class scoped fixtures with pytest-django that need DB access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
from django.contrib.auth.models import User | |
from django.urls import reverse | |
from rest_framework.test import APIClient | |
@pytest.fixture(scope="class") | |
def user(django_db_setup, django_db_blocker): | |
with django_db_blocker.unblock(): | |
user = User.objects.create_user(username="testuser", email="testuser@test.com") | |
user.save() | |
return user | |
@pytest.fixture(scope="class") | |
def authenticated_client(django_db_setup, django_db_blocker, request, user): | |
with django_db_blocker.unblock(): | |
client = APIClient() | |
client.force_authenticate(user) | |
request.cls.client = client | |
@pytest.mark.usefixtures("authenticated_client") | |
class TestUserManagement: | |
@pytest.mark.django_db | |
def test_get_users(self): | |
url = reverse(viewname="users") | |
response = self.client.get(url) | |
assert response.status_code == 200 | |
@pytest.mark.django_db | |
def test_add_user(self): | |
url = reverse(viewname="users") | |
response = self.client.post( | |
url, data={"username": "testuser", "email": "foo@bar.de"} | |
) | |
assert response.status_code == 200 | |
assert User.objects.exists() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment