For certain pages in a Flask app I'm creating, I have an HTTPS redirection system as follows.
def requires_https(f, code=302):
"""defaults to temp. redirect (301 is permanent)"""
@wraps(f)
def decorated(*args, **kwargs):
passthrough_conditions = [
request.is_secure,
request.headers.get('X-Forwarded-Proto', 'http') == 'https',
'localhost' in request.url
]
if not any(passthrough_conditions):
if request.url.startswith('http://'):
url = request.url.replace('http://', 'https://')
r = redirect(url, code=code)
return r
return decorated
If you're not requesting the HTTPS version of the page, it redirects you to it. I want to write unit tests for this service. I have written one that makes sure that you're redirected to the HTTPS version (check for a 301 or a 301, basically). I want to test that if you are requesting the https version of the page and are already on https, it does not redirect you (basically, for a 200). How do I get Flask to send an https request in the unit test?
First create a file named test_app.py and make sure there isn't an __init__.py in your directory. Open your terminal and cd to your directory then run python3 app.py . If you are using windows then run python app.py instead. Hope this will help you solve your problem.
Here's an example below. import pytest from app import create_app @pytest. fixture def request_context(): """create the app and return the request context as a fixture so that this process does not need to be repeated in each test """ app = create_app('module.
Testing Flask requires that we first import a Flask instance app from our api (created in our application), as seen in the previous snippet. The imported instance then exposes a test_client() method from Flask that contains the features needed to make HTTP requests to the application under test.
There's a even easier Flask way to do that, just use the PREFERRED_URL_SCHEME
configuration parameter equals to 'https'.
You can find it's definition here. You can find the rules how it's used internally by Flask here. You can also find how its used here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With