Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Testing

Flask Testing

Testing is the foundation of code quality.

Flask provides a built-in test client, which, combined with pytest, allows you to write and run tests efficiently.


The test client - test_client

Flask's test_client() method creates a simulated HTTP client that can send requests without starting a server:

Example

File path: test_demo.py (tested in the Python interactive environment)

from

app

import

create_app

Create an app instance for testing

app

=

create_app

(

)

Create a test client

with

app.

test_client

(

)

as

client:

   

Send a GET request

    response

=

client.

get

(

"/"

)

   

print

(

response.

status_code

)

 

200

   

print

(

response.

data

[

:

100

]

)

   

The first 100 bytes of the response body

   

Send a POST request and send data as JSON

    response

=

client.

post

(

"/api/posts"

,

                          json

=

{

"title"

:

"RUNOOB tutorial"

,

"body"

:

"Content"

,

"author_id"

:

1

}

)

   

print

(

response.

status_code

)

 

201

   

print

(

response.

get_json

(

)

)

   

Parse the JSON response


pytest integration

pytest is the standard testing framework in the Python community and works very conveniently with Flask.

Install pytest



(.venv) $ pip install pytest

Writing tests - conftest.py (shared fixtures)

Use a conftest.py file to create reusable test fixtures:

Example

File path: tests/conftest.py

import

os

import

tempfile

import

pytest

from

app

import

create_app

from

db

import

init_db

,

get_db

@

pytest.

fixture

def

app

(

)

:

   

"""Create an app instance for testing, using a temporary database"""

   

Create a temporary file to serve as the test database

    db_fd

,

db_path

=

tempfile

.

mkstemp

(

)

   

Create the app, overriding the database path to the temporary file

    app

=

create_app

(

)

    app.

config

[

"DATABASE"

]

=

db_path

    app.

config

[

"TESTING"

]

=

True

 

Enable testing mode

   

Initialize the test database schema

   

with

app.

app_context

(

)

:

        init_db

(

)

   

yield

app

   

Clean up after the test: close and delete the temporary database file

   

os

.

close

(

db_fd

)

   

os

.

unlink

(

db_path

)

@

pytest.

fixture

def

client

(

app

)

:

   

"""Create a test client"""

   

return

app.

test_client

(

)

@

pytest.

fixture

def

runner

(

app

)

:

   

"""Create a CLI test runner"""

   

return

app.

test_cli_runner

(

)


Test routes

Example

File path: tests/test_app.py

def

test_home_page

(

client

)

:

   

"""Test that the homepage returns normally"""

    response

=

client.

get

(

"/"

)

   

assert

response.

status_code

==

200

   

Check that the page contains the expected keyword

   

assert

b

"RUNOOB"

in

response.

data

def

test_404_page

(

client

)

:

   

"""Test accessing a page that does not exist"""

    response

=

client.

get

(

"/this-page-does-not-exist"

)

   

assert

response.

status_code

==

404

Run the tests:



(.venv) $ pytest tests/test_app.py -v

====================================

tests/test_app.py::test_home_page PASSED

tests/test_app.py::test_404_page PASSED

====================================


Test the JSON API

Example

File path: tests/test_api.py

def

test_create_post

(

client

)

:

   

"""Test the API for creating an article"""

    response

=

client.

post

(

"/api/posts"

,

json

=

{

       

"title"

:

"RUNOOB test article"

,

       

"body"

:

"This is test content"

,

       

"author_id"

:

1

   

}

)

   

A successful creation should return 201

   

assert

response.

status_code

==

201

    data

=

response.

get_json

(

)

   

assert

data

[

"title"

]

==

"RUNOOB test article"

   

assert

"id"

in

data

def

test_create_post_without_title

(

client

)

:

   

"""Test that an empty title returns a 400 error"""

    response

=

client.

post

(

"/api/posts"

,

json

=

{

       

"title"

:

""

,

       

"body"

:

"Content"

,

       

"author_id"

:

1

   

}

)

   

assert

response.

status_code

==

400

   

assert

b

"error"

in

response.

data

def

test_get_posts

(

client

)

:

   

"""Test retrieving the article list"""

   

First create an article

    client.

post

(

"/api/posts"

,

json

=

{

       

"title"

:

"Article A"

,

"body"

:

"Content A"

,

"author_id"

:

1

   

}

)

   

Get the list

    response

=

client.

get

(

"/api/posts"

)

   

assert

response.

status_code

==

200

    data

=

response.

get_json

(

)

   

assert

len

(

data

)

=

1

def

test_delete_post

(

client

)

:

   

"""Test deleting an article"""

   

Create first

    rv

=

client.

post

(

"/api/posts"

,

json

=

{

       

"title"

:

"To be deleted"

,

"body"

:

"Content"

,

"author_id"

:

1

   

}

)

    post_id

=

rv.

get_json

(

)

[

"id"

]

   

Then delete

    rv

=

client.

delete

(

f

"/api/posts/{post_id}"

)

   

assert

rv.

status_code

==

200

   

Confirm it has been deleted

    rv

=

client.

get

(

f

"/api/posts/{post_id}"

)

   

assert

rv.

status_code

==

404


Testing Session

Test features that require Session, such as login:

Example

File path: tests/test_auth.py

def

test_login

(

client

)

:

   

"""Test the login flow"""

   

Send a login request

    response

=

client.

post

(

"/auth/login"

,

data

=

{

       

"username"

:

"testuser"

,

       

"password"

:

"testpass"

   

}

,

follow_redirects

=

True

)

 

follow_redirects automatically follows redirects

   

assert

response.

status_code

==

200

def

test_session_transaction

(

client

)

:

   

"""Test by manipulating the session directly"""

   

with

client.

session_transaction

(

)

as

session:

       

Set values directly in the session to simulate a logged-in state

        session

[

"username"

]

=

"runoob"

   

Now visit the homepage; it should show a logged-in state

    response

=

client.

get

(

"/"

)

   

assert

b

"runoob"

in

response.

data

client.session_transaction() is a very practical testing tool - it lets you modify the Session content directly without going through the full login flow.


Testing CLI commands

Example

File path: tests/test_cli.py

def

test_init_db

(

runner

)

:

   

"""Test the database initialization command"""

    result

=

runner.

invoke

(

args

=

[

"init-db"

]

)

   

If the command succeeds, exit_code should be 0

   

assert

result.

exit_code

==

0

def

test_flask_routes

(

runner

)

:

   

"""Test the flask routes command"""

    result

=

runner.

invoke

(

args

=

[

"routes"

]

)

   

assert

result.

exit_code

==

0

   

Check that the output contains the registered routes

   

assert

"/api/posts"

in

result.

output


Testing Best Practices

Practice Description
Use a temporary database Use a separate database for each test so they do not interfere (such as tempfile in conftest.py)
Enable TESTING mode app.config["TESTING"] = True lets exceptions propagate normally instead of being swallowed by error handling
One test should test only one thing Each test function verifies only one behavior, making it easier to locate problems
Use clear names Function names take the form test_scenario_expected_result
Make good use of follow_redirects Useful when testing flows that redirect after a POST

Run all tests



(.venv) $ pytest tests/ -v



tests/test_app.py::test_home_page PASSED

tests/test_app.py::test_404_page PASSED

tests/test_api.py::test_create_post PASSED

tests/test_api.py::test_create_post_without_title PASSED

tests/test_api.py::test_get_posts PASSED

tests/test_api.py::test_delete_post PASSED

tests/test_auth.py::test_login PASSED

tests/test_auth.py::test_session_transaction PASSED

tests/test_cli.py::test_init_db PASSED

tests/test_cli.py::test_flask_routes PASSED



==================== 10 passed in 0.45s ====================