Django messages middleware issue while testing post request
I found the solution. In order to test a such request, you need first to annotate it with a session and then a messages. Actually it means to add these lines:
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
# in your test method:
"""Annotate a request object with a session"""
middleware = SessionMiddleware()
middleware.process_request(req)
req.session.save()
"""Annotate a request object with a messages"""
middleware = MessageMiddleware()
middleware.process_request(req)
req.session.save()
# and then (in my case)
resp = views.LangUpdateView.as_view()(req, pk=langues.pk)
You can also move manual request annotation int a separate context manager that can be reused within multiple tests, the code would look like this then:
import contextlib
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
@contextlib.contextmanager
def middleware(request):
"""Annotate a request object with a session"""
middleware = SessionMiddleware()
middleware.process_request(request)
request.session.save()
"""Annotate a request object with a messages"""
middleware = MessageMiddleware()
middleware.process_request(request)
request.session.save()
yield request
def test_authenticated_staff(self, rf):
langues = LanguageCatalog.objects.create(
lang_src='wz',
lang_dest='en',
percent='4'
)
req = rf.get(reverse("dashboard.staff:lang-update", kwargs={'pk': langues.pk}))
data = {'lang_src': 'it',
'lang_dest': 'en',
'percent': '34'}
req = rf.post(reverse("dashboard.staff:lang-update", kwargs={'pk': langues.pk}), data=data)
req.user = UserFactory()
with middleware(req): # << !
resp = views.LangUpdateView.as_view()(req, pk=langues.pk)