Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django testing and middleware

I am having problems using the Django test Client() for testing middleware. It seems to emulate the sessions middleware specifically. However, since it is based on the RequestFactory, it does not seem to run any middleware.

Is there any way to get the test Client to apply middleware for both, the request and the response? I understand that there are often other ways of specifically testing middleware. However, in certain cases, I would like to test a request with the full middleware stack. Any way of doing this?

I was thinking of extending the Client and modifying its request() class and running the request through the middleware stack at the beginning of the function, and the response through the middleware stack at the bottom of the function. Do you think such a thing would work? If not, can you point me at some resources which would explain why?

like image 984
Krystian Cybulski Avatar asked Dec 06 '12 15:12

Krystian Cybulski


People also ask

What is middleware in Django?

It’s a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, AuthenticationMiddleware, that associates users with requests using sessions.

What is a test client in Django?

The test client is a Python class that acts as a dummy web browser, allowing you to test your views and interact with your Django-powered application programmatically. Simulate GET and POST requests on a URL and observe the response – everything from low-level HTTP (result headers and status codes) to page content.

What are some of the best testing tools for Django?

A short list includes: Continuous Integration: automatically run all tests whenever a new commit is made, which can be done using Github Actions or a service like Travis CI. pytest: pytest is the most popular enhancement to Django and Python's built-in testing tools, allowing for more repeatable tests and a heavy use of fixtures.

What is unit testing in Django?

Testing is an important but often neglected part of any Django project. In this tutorial we'll review testing best practices and example code that can be applied to any Django app. Broadly speaking there are two types of tests you need to run: Unit Tests are small, isolated, and focus on one specific function.


1 Answers

You may need override_settings.

See https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.override_settings.

@override_settings(MIDDLEWARE_CLASSES=(
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
))
class ViewTest(TestCase):

    def setUp(self):
        pass
like image 77
Vinta Avatar answered Sep 22 '22 20:09

Vinta