Search⌘ K

Creating Some Tests: Running Tests

Explore how to create and run tests for your Flask API application, using functions to simulate user interactions and multiple test executions. Understand the role of assertions in testing and learn how to manage them for effective debugging and production readiness.

Next, we’ll create a function that puts the API through its paces to play a game. To do this, we’ll need to create some random strings to enter the username, a task we enable with the random_string function.

Testing the game one time

The test functions can then be tested using the flask shell. Here’s an example of what that might look like, starting in the langman directory.

C++
$ pipenv shell
Launching subshell in virtual environment...
(langman) $ ls
Pipfile Pipfile.lock api_test.py client data server
(langman) $ export FLASK_APP=server.app
(langman) $ export FLASK_ENV=dev_postgres
(langman) $ flask shell
...
Python 3.7.5 (default, Nov 14 2019, 21:33:50)
[Clang 11.0.0 (clang-1100.0.33.12)] on darwin
App: server.app [dev_postgres]
Instance: /Users/.../langman/instance
>>> from api_test import *
>>> app2 = test_app()
Traceback (most recent call last):
...
Failed: Fixture "test_app" called directly.
Fixtures are not meant to be called directly
...
>>> app.config['TESTING'] = True
>>> test_app = app.test_client()
>>> ctx = app.app_context()
>>> ctx.push()
>>> test_full_random_game(test_app)

This example shows us that we can interactively use the application with the flask shell command where the FLASK_APP environment variable has been specified. However, within that shell, we can’t simply run the tests. Instead, we’ll have ...