Django WebTest

1.9.14 · active · verified Thu Apr 16

django-webtest is a Python library that provides instant integration of Ian Bicking's WebTest with Django's testing framework. It offers a `django.test.TestCase` subclass (`django_webtest.WebTest`) that wraps a `webtest.TestApp` around the Django WSGI interface, enabling high-level functional and integration testing. The library is actively maintained, with frequent updates to ensure compatibility with the latest Django and Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a basic functional test using `django_webtest.WebTest`. It shows how to perform GET requests, interact with forms, simulate user login, and assert properties of the response, such as status code and content. Remember to replace `home_page`, `login_page`, and `profile_page` with actual URL names from your Django project. The `fixtures` attribute is optional and allows loading initial data for tests.

from django_webtest import WebTest
from django.urls import reverse

class MyBasicTests(WebTest):
    fixtures = ['users'] # Optional: if you need initial data, e.g., for login

    def test_homepage_access(self):
        # Simulate a GET request to the homepage
        resp = self.app.get(reverse('home_page'))
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Welcome', resp.text)

    def test_login_form_submission(self):
        # Simulate login as a specific user
        login_page = self.app.get(reverse('login_page'))
        form = login_page.form
        form['username'] = 'testuser'
        form['password'] = 'testpassword'
        resp = form.submit().follow()
        self.assertEqual(resp.status_code, 200)
        self.assertIn('Logged in as testuser', resp.text)

    def test_authenticated_page(self):
        # Make an authenticated request using the user argument
        user_resp = self.app.get(reverse('profile_page'), user='testuser')
        self.assertEqual(user_resp.status_code, 200)
        self.assertIn('User Profile for testuser', user_resp.text)

view raw JSON →