Skip to content
Snippets Groups Projects
Verified Commit 8e5ae6ed authored by Teemu Autto's avatar Teemu Autto
Browse files

Simple flask test.

parent a56c3986
No related branches found
No related tags found
1 merge request!12Week 2 example
Pipeline #12914 passed
import pytest
from flask import Flask
from tjts5901.app import create_app
@pytest.fixture
def app():
"""
Application fixture.
Every test that requires `app` as parameter can use this fixture.
Example:
>>> def test_mytest(app: Flask):
>>> ...
"""
_app = create_app({
'TESTING': True,
'DEBUG': False,
# We need to set SERVER_NAME and PREFERRED_URL_SCHEME for testing.
'SERVER_NAME': 'localhost',
'PREFERRED_URL_SCHEME': 'http',
})
# If you have done ties4080 course and have used Flask-WTF, you might
# have noticed that CSRF protection is enabled by default. This is
# problematic for testing, because we don't have a browser to generate
# CSRF tokens. We can disable CSRF protection for testing, but we need
# to make sure that we don't have CSRF protection enabled in production.
# _app.config['WTF_CSRF_ENABLED'] = False
# _app.config['WTF_CSRF_METHODS'] = []
# _app.config['WTF_CSRF_CHECK_DEFAULT'] = False
_app.testing = True
yield _app
# Do some cleanup here if needed.
...
@pytest.fixture
def client(app: Flask):
"""
Setup testing client.
See:
https://flask.palletsprojects.com/en/2.2.x/testing/#the-testing-skeleton
https://werkzeug.palletsprojects.com/en/2.2.x/test/#werkzeug.test.Client
"""
# Setup all the context needed for client to work.
with app.test_client() as test_client:
with app.app_context():
yield test_client
"""
Flask based tests
=================
Uses the flask testclient to retrieve and post pages in application.
"""
from flask.testing import FlaskClient
# This is the string we are looking for in the frontpage.
IN_TITLE = "TJTS5901"
def test_fetch_mainpage(client: FlaskClient):
"""
Fetch frontpage and check that it has <title>.
:param client: Flask test client. See conftest.py for more info how it is
created.
"""
# Request frontpage
page = client.get('/')
# Check that page contains something.
# Note about assert; assert is special kind of keyword. By default
# assert statements are run, but if they are deemed too costly, python
# interepter can be defined to pass them with `python -O` flag.
# If assert statement return False, new assert exception is raised, and
# and test is deemed to fail. After first statement - condition - human
# readable reason for failure can be provided.
# >>> assert (condition-for-failure, "human readable reason")
assert page, "Did not get anything"
assert IN_TITLE.encode() in page.data, f"Page didn't have {IN_TITLE}"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment