Flask generated page - time tested


How can we test the version of our application that also has a generated page? We need to test two pages.

There are many ways to divide our tests.

Putting them in separate functions allows us to run them separately. It also means that if one fails the other might still pass. Usually we put independent test-cases in separate functions. Because it is still so small, putting them in two separate files seems to be an overkill.

The test_home function is relatively straight forward. We get the main page and then we check the status-code and the exact match for the content.

The test_time function is trickier. We can't check an exact match as the timestamp will be different every time we run the code. We could mock the time, but we are looking for a simpler solution. So instead of an exact match we use a regexp to check if the result looks like a number we would expect.

You can run the tests by running pytest.


examples/flask/time/test_app.py
import app
import re

def test_home():
    web = app.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data == b'<a href="/time">time</a>'

def test_time():
    web = app.app.test_client()

    rv = web.get('/time')
    assert rv.status == '200 OK'
    assert re.search(r'\d+\.\d+$', rv.data.decode('utf-8'))

pytest