Flask Testing our Hello World app



In this minimalist example, using pytest we're going to test that indeed our Hello World app does return "Hello, World!" with an HTTP OK status code of 200, when hit with a GET request on the URL /

First let's install pytest into our virtualenv

pip install pytest

And just for reference, this our hello world app:

# hello.py
from flask import Flask

app = Flask(__name__)

def hello():
    return 'Hello, World!'

Defining the test

Along side our hello.py, we define a test module called test_hello.py that is going to be discovered by py.test

# test_hello.py
from hello import app

def test_hello():
    response = app.test_client().get('/')

    assert response.status_code == 200
    assert response.data == b'Hello, World!'

Just to review, at this point our project structure obtained with the tree command is:

├── hello.py
└── test_hello.py

Running the test

Now we can run this test with the py.test command that will automatically discover our test_hello.py and the test function inside it

$ py.test

You should see some output and an indication that 1 test has passed, e.g.

=== test session starts ===
collected 1 items 
test_hello.py .
=== 1 passed in 0.13 seconds ===