Testing URLs in Flack Redirects

If POST is successfully sent to the endpoint of the form, I redirect back to the same endpoint with some URL parameters that my client side code can interact with.

@bp.route('/submit', methods=['GET', 'POST']) def submit(): form = SubmissionForm() labels = current_app.config['TRELLO_LABELS'] if form.validate_on_submit(): submission = Submission().create( title=form.data['title'], email=form.data['email'], card_id=card.id, card_url=card.url) # reset form by redirecting back and setting the URL params return redirect(url_for('bp.submit', success=1, id=card.id)) return render_template('submit.html', form=form) 

But I ran into some problems trying to write a test for this code, since I cannot figure out how to verify that these URL parameters are in my redirect URL. My incomplete test code:

 import pytest @pytest.mark.usefixtures('session') class TestRoutes: def test_submit_post(self, app, mocker): with app.test_request_context('/submit', method='post', query_string=dict( email=' email@example.com ', title='foo', pitch='foo', format='IN-DEPTH', audience='INTERMEDIATE', description='foo', notes='foo')): assert resp.status_code == 200 

I tried several different methods to test this. With and without a context manager, I test_client deep into the source of Flask and Werkzeug on the pages test_client and test_request_context .

I just want to verify that the URL parameters for success and id exist when redirecting after a valid POST.

+5
source share
2 answers

Here's a super simple but inclusive example of fixing the Flask url_for method (can be run as-in in the Python interpreter):

 import flask from unittest.mock import patch @patch('flask.url_for') def test(self): resp = flask.url_for('spam') self.assert_called_with('spam') 


However, the above example will only work if you import Flask directly and do not use from flask import url_for in your route code. You will need to fix the exact namespace, which will look something like this:

 @patch('application.routes.url_for') def another_test(self, client): # Some code that envokes Flask url_for, such as: client.post('/submit', data={}, follow_redirects=True) self.assert_called_once_with('bp.submit', success=1, id=1) 

For more information, check out Where to Patch in the mock documentation.

+3
source

You can use the mock function the patch function to schedule url_for by grabbing the provided arguments and then testing them.

0
source

Source: https://habr.com/ru/post/1274804/


All Articles