Skip to content

Instantly share code, notes, and snippets.

@wolkenarchitekt
Last active February 27, 2020 09:32
Show Gist options
  • Save wolkenarchitekt/1c1784ad6592bd7a20f884d7ac1a67f3 to your computer and use it in GitHub Desktop.
Save wolkenarchitekt/1c1784ad6592bd7a20f884d7ac1a67f3 to your computer and use it in GitHub Desktop.
Using class scoped fixtures with pytest-django that need DB access
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