Django 1.9 unittest error for messages but i dont

2019-09-11 03:52发布

问题:

The test fails with the error in Django 1.9 env, but tests run perfectly well in 1.10.4 and 1.8. Can someone throw some light here !

Here is the error

add_message raise MessageFailure('You cannot add messages without installing ' MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

Check https://travis-ci.org/invaana/Hydronium/builds/182190626 for complete errors

views.py

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Operation Successful! This is demo. Im not sending any messages')
        else:
            form.errors
            messages.error(request, 'Message not sent, Please fix the errors!.' )
    else:
        form = ContactForm()
    return render(request, 'pages/contact.html', {'form': form})

tests.py

def test_contactform_valid(self):
    res = self.client.post(reverse('contact'), {'name':'Ravi','email':'rrmerugu@gmail.com', 'text': 'im good' })
    self.assertIn('Operation Successful', res.content)

def test_contactform_invalid(self):
    res = self.client.post(reverse('contact'), {'name':'Ravi','email':'rrmerugu@gmail.com', 'text': '' })
    self.assertIn('Message not sent', res.content)

回答1:

Apparently,

MIDDLEWARE_CLASSES is used in 1.9, 1.8

MIDDLEWARE is used in 1.10.4.

To make the middleware compatible for both, I used the following code in settings.py

MIDDLEWARE = MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]