On each of my view I have a function that return the request language code of the browser. But when I run my unittest my views I have an error:
applications\emplois\views.py:74:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <applications.emplois.views.IndexView object at 0x0000000006270048>
def language(self):
"""Return the user default language"""
> language = language_set(self.request.LANGUAGE_CODE)
E AttributeError: 'WSGIRequest' object has no attribute 'LANGUAGE_CODE'
applications\emplois\views.py:64: AttributeError
---------------------------- Captured stdout setup ----------------------------
Creating test database for alias 'default'...
=================== 1 failed, 11 deselected in 5.97 seconds ===================
views.py
def language_set(language):
if "-" in language:
return (language.split('-')[1]).upper()
else:
return language.upper()
class IndexView(generic.ListView):
"""
this is the ROOT page
return a list of Jobs
"""
template_name='emplois/index.html'
context_object_name='latest_jobs_list'
paginate_by = 10
def language(self):
"""Return the user default language"""
language = language_set(self.request.LANGUAGE_CODE)
language = language.upper()
return language
def get_queryset(self):
"""
Return a list of Jobs that have an EXPIRATION DATE
greater than Now() and a default Language
"""
#import ipdb;ipdb.set_trace()
return Job.objects.filter(language=self.language(),\
EXPIRYDATE__gt=datetime.now())\
.order_by('EXPIRYDATE')
tests:
import pytest
from django.core import mail
from django.contrib.auth.models import AnonymousUser
from django.http import Http404
from django.test import RequestFactory
from mock import patch
from mixer.backend.django import mixer
pytestmark = pytest.mark.django_db
from applications.emplois import views
class TestIndexView:
def test_anonymous(self):
req = RequestFactory().get('/')
resp = views.IndexView.as_view()(req)
assert resp.status_code == 200, 'Should be callable by anyone'
How can I bypass the Language request because I don't use a browser
When you use a RequestFactory
you can give the request any request parameters. In this case you are looking for the request.LANGUAGE_CODE
so the solution is to set the LANGUAGE_CODE
in your test's RequestFactory
.
You can see the documentation for the RequestFactory
here.
So solution is:
def test_anonymous(self):
req = RequestFactory().get('/')
# Here is the change.
req.LANGUAGE_CODE = "en"
resp = views.IndexView.as_view()(req)
assert resp.status_code == 200, 'Should be callable by anyone'