Repository navigation
Unit tests for flasked
Iván de Paz Centeno edited this page Jan 9, 2018
·
2 revisions
Flasked can be tested in the same way a flask application. The following example illustrates a simple test case for a simple API.
Given the following definition:
from flasked import Flasked
class Root():
def get(self):
return {'foo': 'bar'}
def create_app():
flasked = Flasked()
flasked["/"] = Root
return flaskedNote that the creation of the app is encapsulated inside a function. This is a good practice, as it allows us to just create the APP and delegate its running to other tools, like Tornado, or in this case, the unit-testing framework.
Indeed, it can be tested as follows:
import unittest
import json
from main_file import create_app
class TestApp(unittest.TestCase):
def setUp(self):
# We create the app but we don't run it.
self.flasked = create_app()
def test_root(self):
# We haven't ran the application but we can still test it by using the `test_client`.
client = self.flasked.flask_app.test_client()
# The test_client allows us to invoke the get() of any route.
response = client.get("/")
response_json = json.loads(str(response.data, 'UTF-8'))
self.assertEquals(response.status_code, 200)
self.assertEquals(response_json, {'foo': 'bar'})
if __name__ == '__main__':
unittest.main()