# Import all dependencies
import unittest
import json
from flaskr import create_app
from models import setup_db
# Define Test Case Class
# Class name should be intuitive
class AppNameTestCase(unittest.TestCase):
# setUp run before each test
def setUp(self):
# Executed before each test. Define test variables and initialize app.
self.client = app.test_client
pass
# testDown run after each test
def tearDown(self):
# Execute after each test
pass
# 最主要部分
# tests client request and evaluate response
def test_given_behavior(self):
res = self.client().get('/')
self.assertEqual(res.status_code, 200)
# Make the tests conveniently executable
if __name__ == "__main__":
unittest.main()
总结一下:
Unit test Flask Key Structures
- Define the test case class for the application (or section of the application, for larger applications).
- Define and implement the
setUp
function. It will be executed before each test and is where you should initialize the app and test client, as well as any other context your tests will need. The Flask library provides a test client for the application. - Define the
tearDown
method, which is implemented after each test. It will run as long assetUp
executes successfully, regardless of test success. - Define your tests. All should begin with
test_
and include a doc string about the purpose of the test. In defining the tests, you will need to:- Get the response by having the client make a request
- Use
self.assertEqual
to check the status code and all other relevant operations.
- Run the test suite, by running
python test_file_name.py
from the command line.