Search code examples
pythonflaskpytesthttp-status-code-400

Assertion Error (200 Success != 400 Bad Request) while unit testing a Dockerized Flask App


Okay, I am struggling with this problem for 2 days now. When I am manually posting data in the form in the browser, everything works fine, and I am getting the flash message that should say 'Thanks...'. While testing my Flask application, this test does not pass because I am getting a 400 Bad Request error while sending a post request on my Flask form. To be clear, I am using Flask-Mail and WTForms for the form, and my application is dockerized and also running redis and celery. I am kinda new to these stuff, so if my question is not clear enough, please be kind and tell me if I should provide more detailed info. Thanks, and here is the relevant code and the error that is shown while testing with py.test. And sorry about the links, I am still not allowed to post pictures on StackOverflow.

The error code: Pytest Assertion Error

contact/forms.py:

from flask_wtf import FlaskForm
from wtforms import TextAreaField, StringField
from wtforms.validators import DataRequired, Length, Email


class ContactForm(FlaskForm):
    email = StringField("What's your e-mail address?",
                        [Email(), DataRequired(), Length(3, 254)])
    message = TextAreaField("What's your question or issue?",
                            [DataRequired(), Length(1, 8192)])

contact/views.py:

from flask import (
    Blueprint,
    flash,
    redirect,
    request,
    url_for,
    render_template)

from flexio.blueprints.contact.forms import ContactForm

contact = Blueprint('contact', __name__, template_folder='templates')


@contact.route('/contact', methods=['GET', 'POST'])
def index():
    form = ContactForm()

    if form.validate_on_submit():
        # This prevents circular imports.
        from flexio.blueprints.contact.tasks import deliver_contact_email

        deliver_contact_email(request.form.get('email'),
                                    request.form.get('message'))

        flash('Thanks, expect a response shortly.', 'success')
        return redirect(url_for('contact.index'))

    return render_template('contact/index.html', form=form)

contact/tasks.py:

from lib.flask_mailplus import send_template_message
from flexio.app import create_celery_app

celery = create_celery_app()


@celery.task()
def deliver_contact_email(email, message):
    """
    Send a contact e-mail.

    :param email: E-mail address of the visitor
    :type user_id: str
    :param message: E-mail message
    :type user_id: str
    :return: None
    """
    ctx = {'email': email, 'message': message}

    send_template_message(subject='[Flexio] Contact',
                          sender=email,
                          recipients=[celery.conf.get('MAIL_USERNAME')],
                          reply_to=email,
                          template='contact/mail/index', ctx=ctx)

    return None

lib/tests.py:

def assert_status_with_message(status_code=200, response=None, message=None):
    """
    Check to see if a message is contained within a response.

    :param status_code: Status code that defaults to 200
    :type status_code: int
    :param response: Flask response
    :type response: str
    :param message: String to check for
    :type message: str
    :return: None
    """
    assert response.status_code == status_code
    assert message in str(response.data)

tests/contact/test_views.py:

from flask import url_for
from lib.tests import assert_status_with_message
class TestContact(object):
    def test_contact_page(self, client):
        """ Contact page should respond with a success 200. """
        response = client.get(url_for('contact.index'))
        assert response.status_code == 200
    def test_contact_form(self, client):
        """ Contact form should redirect with a message. """
        form = {
          'email': '[email protected]',
          'message': 'Test message from Flexio.'
        }
        response = client.post(url_for('contact.index'), data=form,
                               follow_redirects=True)
        assert_status_with_message(200, response, 'Thanks')

Solution

  • Your browser will have requested the form with a GET request first, and thus have been given a CSRF token as a cookie and as a hidden form element in the form. When you then submit the form, the CSRF protection passes.

    Your test doesn't make a GET request nor does it use the form fields from the form that such a request makes, so your POST request is missing both the cookie and the hidden field.

    In a test, you could just disable CSRF protection by setting the WTF_CSRF_ENABLED parameter to False:

    app.config['WTF_CSRF_ENABLED'] = False