Example test for a class-based DetailView using pytest
and pytest-django.
Using fixtures from pytest-django
(admin_user and rf) and
one additional fixture for the element used in the DetailView.
import pytest
from django.core.urlresolvers import reverse
from myapp.models import Thing
from myapp.views import ThingDetailView
@pytest.fixture
def thing(admin_user):
(thing_object, created) = Thing.objects.get_or_create(name="test",
created_by=admin_user)
return thing_object
def test_detail_view_logged_in(rf, admin_user, thing):
# set kwargs for reverse and for view
kwargs_thing = {
'pk': thing.id,
}
url = reverse("thing_detail", kwargs=kwargs_thing)
# bind url to request factory
request = rf.get(url)
# set user in request to admin_user
request.user = admin_user
# creates response, given request and kwargs needed for view
response = ThingDetailView.as_view()(request, **kwargs_thing)
assert response.status_code == 200
Tell us what you think about this. Is something unclear? Do you have questions or ideas? Leave your comments below.
comments powered by Disqus